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];
}
参考:
1. http://blog.seancarpenter.net/2012/10/15/scrolling-a-uitableview-when-displaying-the-keyboard/
时间: 2024-10-11 01:42:12