iOS開發-鍵盤通知

一任天然發表於2016-07-27

iOS開發-鍵盤通知

4種常用通知

UIKeyboardWillShowNotification、UIKeyboardDidShowNotification、UIKeyboardDidHideNotification、UIKeyboardDidHideNotification

註冊與解除

addObserver與removeObserver需要在對應的生命週期中成對出現。即有“新增”有“刪除”。

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 註冊鍵盤通知
    // 即將顯示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    // 顯示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];
    // 即將隱藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardDidHideNotification object:nil];
    // 隱藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 接觸鍵盤通知
    // 即將顯示
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    // 顯示
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    // 即將隱藏
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    // 隱藏
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (void) keyboardWillShowNotification: (NSNotification *)notif{
    NSLog(@"鍵盤即將顯示");
}
- (void) keyboardDidShowNotification: (NSNotification *)notif{
    NSLog(@"鍵盤顯示");
}
- (void) keyboardWillHideNotification:(NSNotification *)notif{
    NSLog(@"鍵盤即將隱藏");
}
- (void) keyboardDidHideNotification:(NSNotification *)notif{
    NSLog(@"鍵盤隱藏");
}

相關文章