- 在iOS上有兩個(gè)通知可以監(jiān)聽鍵盤彈出和收回:
UIKeyboardWillShowNotification(彈出)和UIKeyboardWillHideNotification(收回)。可以分別監(jiān)聽兩個(gè)通知調(diào)整輸入框的位置。但也有一個(gè)監(jiān)聽起來更為方便的通知UIKeyboardWillChangeFrameNotification(直接監(jiān)聽鍵盤的frame改變,彈出或收回)代碼如下:
//監(jiān)聽鍵盤彈出或收回通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- 當(dāng)鍵盤frame改變(彈出和收回)時(shí)的操作:
- (void)keyboardChange:(NSNotification *)note{
//拿到鍵盤彈出的frame
CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//修改底部輸入框的約束
self.bottomConstrain.constant = [UIScreen mainScreen].bounds.size.height - frame.origin.y;
//鍵盤彈出所需時(shí)長
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//添加輸入框彈出和收回動畫
[UIView animateWithDuration:duration animations:^{
//立即刷新進(jìn)行重新布局
[self.view layoutIfNeeded];
}];
}
- 移除通知
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

動圖.gif