//首先注册通知,监听键盘:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisAppear:) name:UIKeyboardWillHideNotification object:nil];
}
//在键盘弹出和收起的方法中做以下操作
- (void)keyboardWillAppear:(NSNotification *)noti {
NSDictionary *userInfo = noti.userInfo;
//获取键盘的frame
CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//获取键盘弹出的动画时间
NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey ] doubleValue];
//让输入框跟随变化
[UIView animateWithDuration:animationDuration animations:^{
[_ctv mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(@(-keyboardFrame.size.height));
}];
}];
//设置tableview的contentInset属性,改变tableview的显示范围
_tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardFrame.size.height, 0);
_tableView.scrollEnabled = YES;
}
- (void)keyboardWillDisAppear:(NSNotification *)noti {
NSDictionary *userInfo = noti.userInfo;
NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey ] doubleValue];
[UIView animateWithDuration:animationDuration animations:^{
[_ctv mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(@0);
make.height.equalTo(@52);
}];
}];
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_tableView.contentInset = contentInsets;
}