1.通过storyb搭建view,使用自动布局。注意tableview要以下方输入框为参考。
2. 找到发送框名称为Vertical Space - Bottom Layout Guide的约束,并连线
3. 通过通知中心设置观察者,监听键盘弹出事件
- (void)viewDidLoad {
[super viewDidLoad];
// 设置观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
4. 处理事件
- (void)keyboardFrameChanged:(NSNotification *)n {
NSLog(@"%@", n);
// 取出通知中的 userInfo 中的 CGRect
CGRect rect = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 取出动画时长
NSTimeInterval t = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
// 修改底部约束的数值 - 视图的自动布局就发生了变化
self.bottomConstraint.constant = rect.size.height;
// 动画
[UIView animateWithDuration:t animations:^{
// 自动布局的动画,如果需要重新布局
[self.view layoutIfNeeded];
}];
}