您的位置:首页 > 移动开发 > IOS开发

ios键盘弹起tableView的滑动区域问题

2017-10-11 10:20 225 查看
在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显示所有内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: