在通知中心建立一個廣播來監聽鍵盤的彈出和彈回,在監聽事件中加入觸發事件的一些操作。
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardwillhide:) name:UIKeyboardWillHideNotification object:nil];
監聽鍵盤的一些通知:
// 鍵盤的frame發生改變時發出的通知(位置和尺寸)// UIKeyboardWillChangeFrameNotification// UIKeyboardDidChangeFrameNotification// 鍵盤顯示時發出的通知// UIKeyboardWillShowNotification// UIKeyboardDidShowNotification// 鍵盤隱藏時發出的通知// UIKeyboardWillHideNotification// UIKeyboardDidHideNotification
在這里我需要實現的效果(如下圖)是在在鍵盤彈出時,使下方的toolbar向上移動到相應位置,因此需要知道鍵盤的高度和彈出動畫的時間,通過廣播監聽來得到鍵盤的frame和彈出動畫時間:
NSString *duration = userInfo[UIKeyboardAnimationDurationUserInfoKey];CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
再通過動畫效果,改變tableview和toolbar的frame,使得鍵盤在彈出時不會被遮擋:
[UIView animateWithDuration:[duration doubleValue] delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{_tableview.frame = CGRectMake(0, 64 , SIZE.width, SIZE.height - 64 - keyboardFrame.size.height - 50);footView.frame = CGRectMake(0, SIZE.height - keyboardFrame.size.height - 50, SIZE.width, 50);} completion:^(BOOL finished) {NSIndexPath *path = [NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0];[_tableview scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];}];
效果圖: