鍵盤彈出後擋住列表底部的輸入框,是聊天類、評論類介面最常見的困擾。處理思路其實很清晰:監聽鍵盤通知、依鍵盤高度縮短列表、滾動到目前編輯的儲存格。
在初始化方法或 viewDidLoad 中註冊,並務必在 dealloc 中移除觀察者,避免懸空指標。
-(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// 也可以寫在 viewDidLoad 中
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardShown:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardHidden:)
name:UIKeyboardDidHideNotification
object:nil];
}
return self;
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidHideNotification
object:nil];
}
注意要先把鍵盤座標從視窗座標系轉換到自身視圖座標系,再據此縮短 tableView 高度;鍵盤收起時還原,並加上一點動畫緩衝。
-(void)keyboardShown:(NSNotification*)notification {
_initialTVHeight = _tableView.frame.size.height;
CGRect initialFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect convertedFrame = [self.view convertRect:initialFrame fromView:nil];
CGRect tvFrame = _tableView.frame;
tvFrame.size.height = convertedFrame.origin.y;
_tableView.frame = tvFrame;
}
-(void)keyboardHidden:(NSNotification*)notification {
CGRect tvFrame = _tableView.frame;
tvFrame.size.height = _initialTVHeight;
[UIView beginAnimations:@"TableViewDown" context:NULL];
[UIView setAnimationDuration:0.3f];
_tableView.frame = tvFrame;
[UIView commitAnimations];
}
延遲 0.5 秒是為了等鍵盤動畫與列表高度調整都完成後再滾動,否則容易捲到一半被 layout 打斷。
-(void)textFieldDidBeginEditing:(UITextField *)textField {
NSIndexPath* path = [NSIndexPath indexPathForRow:row inSection:section];
[self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0.5f];
}
-(void)scrollToCell:(NSIndexPath*)path {
[_tableView scrollToRowAtIndexPath:path
atScrollPosition:UITableViewScrollPositionNone
animated:YES];
}
這套做法的優點是不依賴任何第三方庫,邏輯一目了然。若你的專案已經導入 IQKeyboardManager 這類成熟方案,也可以直接採用,省去自己維護的負擔。