键盘遮挡处理

作者: KevinTing | 来源:发表于2016-03-01 22:05 被阅读1156次

键盘弹起遮住输入框这个问题是每个iOS开发者绕不过去的坎,那么到底该如何进行键盘处理?
现在有TPKeyboardAvoidingIQKeyboardManager这两个大牛级的库,其实自己做起来也比较简单:

输入框.gif
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardFrameChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)handleKeyboardFrameChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (CGRectIsNull(keyboardEndFrame)) {
        return;
    }
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat height = 0.0;
    if (fabs(keyboardEndFrame.origin.y - screenHeight) > 0.1) {
        height = CGRectGetHeight(keyboardEndFrame);
    }
    double animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    self.bottomConstraint.constant = height;
    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

这里只用监听一个通知UIKeyboardDidChangeFrameNotification即可,并不其他很多文章里面描述的需要监听UIKeyboardWillShowNotification,UIKeyboardDidShowNotification,UIKeyboardWillHideNotification,UIKeyboardDidHideNotification等通知。然后获取keyboardEndFrame的高度即可。

完整项目在这里:https://github.com/tujinqiu/KTAutoHeightTextView

相关文章

网友评论

    本文标题:键盘遮挡处理

    本文链接:https://www.haomeiwen.com/subject/seqwkttx.html