最近項目中用到了在tableView上放UITextField,當UITextField獲取焦點時,鍵盤就會彈起,就會遮擋一部分,這時就需要做一些特殊的處理來防止鍵盤遮擋tableView,其實思路還是很簡單的,系統提供了2個通知,UIKeyboardWillShowNotification和UIKeyboardWillHideNotification,通過名字就能看出來,UIKeyboardWillShowNotification監聽的是鍵盤將要彈出時的事件,UIKeyboardWillHideNotification監聽的是鍵盤將要隱藏時的事件。這兩個通知都包含鍵盤的一些信息,比如通知開始前鍵盤的frame、收到通知後鍵盤的高度等等。我們就在UIKeyboardWillShowNotification的通知事件中改變tableView的frame並將其滾動到最底部,在UIKeyboardWillHideNotification的通知事件中將tableView的frame變成原來的即可。下面是具體的代碼:
(1)註冊通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
(2)添加通知事件:
#pragma mark 鍵盤將要出現的時候
- (void)keyboardWillShow:(NSNotification *)notification {
CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, UI_SCREEN_HEIGHT - endFrame.size.height);
// 這個動畫是爲了兼容第三方輸入法,如果是系統的輸入法直接改變他的ContentOffset即可,默認有動畫,但是如果是第三方輸入法動畫就沒有了,所以在這裏用鍵盤的動畫來進行彌補
[UIView animateWithDuration:duration.doubleValue animations:^{
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:[curve intValue]];
if (self.tableView.contentSize.height > self.tableView.frame.size.height) {
CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
// 這裏的animated屬性必須設置爲NO(即不用系統的動畫),否則會出現問題
[self.tableView setContentOffset:offset animated:NO];
}
}];
}
#pragma mark 鍵盤將要隱藏
- (void)keyboardWillHide:(NSNotification *)notification {
self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, UI_SCREEN_HEIGHT);
}
(3)移除通知:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];