//注册通知
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}
//注销通知
-(void)viewDidDisAppear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
//键盘上弹
-(void)openKeyboard:(NSNotification *)notification{
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
UIViewAnimationOptions option = [notification.userInfo [UIKeyboardAnimationCurveUserInfoKey]intValue];
// self.BottomLayoutConstaint.constant 这个是storyboard里面tableview的下沿,直接拉线的,而keyboardFrame.size.height是键盘的高度
self.BottomLayoutConstaint.constant = keyboardFrame.size.height+99*SizeScaleY;
[UIView animateWithDuration:duration delay:0 options:option animations:^{
[self.view layoutIfNeeded];
} completion:nil];
}
//恢复键盘
-(void)closeKeyboard:(NSNotification *)notification{
self.BottomLayoutConstaint.constant = 0;
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
UIViewAnimationOptions option = [notification.userInfo [UIKeyboardAnimationCurveUserInfoKey]intValue];
[UIView animateWithDuration:duration delay:0 options:option animations:^{
[self.view layoutIfNeeded];
} completion:nil];
}
//tableView滚动的时候自动收回键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
如上面设置就可以实现键盘的上弹和收回了,当然要灵活运用。