1.使用Masnory自动布局
//监控键盘
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
//实现方法:
- (void)keyBoardShow:(NSNotification *)notifation {
self.chatAndContactBtn.userInteractionEnabled = NO;
//获取键盘高度
CGFloat keyboardHeight = [[notifation.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notifation.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//底部视图的 底部约束 根据键盘的弹起而改变
[UIView animateWithDuration:duration animations:^{
[self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.mas_equalTo(-keyboardHeight);
}];
}];
}
- (void)keyBoardHide:(NSNotification *)notifation {
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notifation.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.mas_equalTo(0);
}];
}];
}
2.使用xib自动布局
监听键盘同1,下面是实现监听方法
viewToBottomViewConstraint:该属性是从xib上拉取的约束,键盘变化更新约束即可。
#pragma mark ------ notification
- (void)willShowKeyboard:(NSNotification *)noti {
//获取键盘高度
CGFloat keyboardHeight = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.viewToBottomViewConstraint.constant = keyboardHeight+66;
[UIView animateWithDuration:duration
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[self.view layoutIfNeeded];
}
completion:^(BOOL finished){
}];
}
- (void)willHideKeyboard:(NSNotification *)noti {
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.viewToBottomViewConstraint.constant = 66;
[UIView animateWithDuration:duration
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[self.view layoutIfNeeded];
}
completion:^(BOOL finished){
}];
}