1、首先在ViewDidLoad里面添加注册键盘隐藏与出现的通知:
///< 注册通知,以便在键盘将要出现时,调整页面 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; ///< 注册通知,以便在键盘将要隐藏时,恢复页面 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2、在viewWillDisappear里移除对键盘隐藏与出现的通知:
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; /// 注意:在此处需要移除通知,否则容易照成崩溃 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; return; }
3、实现键盘出现、隐藏时的通知回调:
#pragma mark - UIKeyboardWillShowNotification 通知 - (void)onKeyboardWillShow:(NSNotification *)notification { CGRect frame = self.view.frame; if (frame.origin.y < 0) { return; } // 获取键盘的高度 CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification]; frame.origin.y -= (keyboardHeight - 20); [UIView animateWithDuration:0.35 animations:^{ self.view.frame = frame; }]; return; } #pragma mark - UIKeyboardWillHideNotification 通知 - (void)onKeyboardWillHide:(NSNotification *)notification { CGRect frame = self.view.frame; if (frame.origin.y > 0) { return; } // 获取键盘的高度 CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification]; frame.origin.y += (keyboardHeight - 20); [UIView animateWithDuration:0.35 animations:^{ self.view.frame = frame; }]; return; } /// 获取键盘高度 - (CGFloat)keyboardHeightWithKeyboardNotification:(NSNotification *)notification { NSDictionary *info = notification.userInfo; NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyboardSize = [value CGRectValue].size; CGFloat keyboardHeight = keyboardSize.height; return keyboardHeight; }