1.先添加對(duì)鍵盤的監(jiān)聽
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
當(dāng)系統(tǒng)消息出現(xiàn)UIKeyboardWillShowNotification和UIKeyboardWillHideNotification消息就會(huì)調(diào)用我們的keyboardWillShow和keyboardWillHide方法。
2.實(shí)現(xiàn)監(jiān)聽方法
#pragma mark ---- 根據(jù)鍵盤高度將當(dāng)前視圖向上滾動(dòng)同樣高度
///鍵盤顯示事件
- (void)keyboardWillShow:(NSNotification *)notification {
//獲取鍵盤高度,在不同設(shè)備上,以及中英文下是不同的
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//計(jì)算出鍵盤頂端到inputTextView panel底端的距離(加上自定義的緩沖距離INTERVAL_KEYBOARD)
CGFloat offset = kbHeight;
// 取得鍵盤的動(dòng)畫時(shí)間,這樣可以在視圖上移的時(shí)候更連貫
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//將視圖上移計(jì)算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
}
#pragma mark ---- 當(dāng)鍵盤消失后,視圖需要恢復(fù)原狀
///鍵盤消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
// 鍵盤動(dòng)畫時(shí)間
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//視圖下沉恢復(fù)原狀
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}
3.注銷通知
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
4.然后在這里安利一個(gè)很好的第三方 IQKeyboardManager 特別好用
有需要的可以直接去下載 https://github.com/hackiftekhar/IQKeyboardManager