美文网首页
iOS 手动解决键盘遮挡

iOS 手动解决键盘遮挡

作者: YannChee | 来源:发表于2017-12-26 19:09 被阅读60次

使用 IQKeyboardManager 这个开源库,基本可以应对大部分情况,但是在某些情况下,这个框架会有bug,比如只能自己来实现了

使用KVC监听键盘弹出的通知即可:
这里我是用的是ReactiveCocoa 来实现的

    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillChangeFrameNotification object:nil] subscribeNext:^(id x) {
        NSNotification *noti = x;
        CGFloat duration = [noti.userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue] ;
        //
        CGRect keyboardFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        if (keyboardFrame.origin.y >= self.view.height) { // 键盘未弹出
            [UIView animateWithDuration:duration animations:^{
                //
                self.bottomToolBarView.transform = CGAffineTransformIdentity;
            }];
        } else { // 键盘弹出
            [UIView animateWithDuration:duration animations:^{
                //
                self.bottomToolBarView.transform = CGAffineTransformMakeTranslation(0, -keyboardFrame.size.height);
            }];
        }
    }];

如果有使用IQKeyboardManager,建议在页面关闭IQKeyboardManager的功能

- (void)viewWillAppear:(BOOL)animated {
    // 关闭 IQKeyboardManager
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    //
    [IQKeyboardManager sharedManager].enable = YES;
    
}

相关文章

网友评论

      本文标题:iOS 手动解决键盘遮挡

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