1、注冊
UIKeyboardDidShowNotification/UIKeyboardDidHideNotification通知。
-(id) initWithNibName:(NSString*)nibNameOrNil bundle: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];
}
2、當通知到來,調整frame。
-(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];
}
3、觸發文本框,滾動tableView
-(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];
}