1.先添加對(duì)鍵盤(pán)的監(jiān)聽(tīng)
[[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)聽(tīng)方法
#pragma mark ---- 根據(jù)鍵盤(pán)高度將當(dāng)前視圖向上滾動(dòng)同樣高度
///鍵盤(pán)顯示事件
- (void)keyboardWillShow:(NSNotification *)notification {
//獲取鍵盤(pán)高度,在不同設(shè)備上急侥,以及中英文下是不同的
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//計(jì)算出鍵盤(pán)頂端到inputTextView panel底端的距離(加上自定義的緩沖距離INTERVAL_KEYBOARD)
CGFloat offset = kbHeight;
// 取得鍵盤(pán)的動(dòng)畫(huà)時(shí)間砌滞,這樣可以在視圖上移的時(shí)候更連貫
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//將視圖上移計(jì)算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, self.navigationController.navigationBar.frame.size.height+[[UIApplication sharedApplication] statusBarFrame].size.height - offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
}
#pragma mark ---- 當(dāng)鍵盤(pán)消失后,視圖需要恢復(fù)原狀
///鍵盤(pán)消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
// 鍵盤(pán)動(dòng)畫(huà)時(shí)間
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//視圖下沉恢復(fù)原狀
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, self.navigationController.navigationBar.frame.size.height+[[UIApplication sharedApplication] statusBarFrame].size.height, 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];
}
我在這里使用self.navigationController.navigationBar.frame.size.height+[[UIApplication sharedApplication] statusBarFrame].size.height
來(lái)獲取設(shè)備和 statusBar 和 navigationBar 的高度坏怪,項(xiàng)目中推薦使用宏定義贝润。
默默求贊