iOS 手动解决键盘遮挡

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

使用KVO监听键盘弹出的通知即可:
这里我是用的是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 手动解决键盘遮挡)