在iOS项目开发过程中,经常需要点击textview弹起键盘,但弹起键盘后tableView的可见区域就变小了,如果这时tableView不能在可见区域内滑动,那tableView的内容就不能在键盘弹起的情况下完全显示,这样用户体验就不好了。下面提供一种解决方法。
由于大部分控制器类都需要用到tableView,为此可以写一个公共的父类BaseTableViewController继承自UIViewController,里面初始化tableView并实现其代理方法,设置一个属性
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
核心代码如下:- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.view endEditing:YES];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)dealloc {
NSLog(@"dealloc %@", [self class]);
}
#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)notification {
if (!self.tapGesture) {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
tap.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tap];
self.tapGesture = tap;
}
CGRect keyboardBounds = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, keyboardBounds.size.height, 0);
}
- (void)keyboardWillHide:(NSNotification *)notification {
[self.view removeGestureRecognizer:self.tapGesture];
self.tapGesture = nil;
self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, 0, 0);
}
- (void)viewTapped:(id)sender {
[self.view endEditing:YES];
}
这样子类在继承父类BaseTableViewController时,可在键盘弹起的情况下滑动tableView显示所有内容。