键盘遮挡处理

键盘弹起遮住输入框这个问题是每个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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容