iOS 键盘遮挡处理办法(不用键盘高度计算)

注册观察者观察系统通知用以观察键盘事件


///键盘显示事件

- (void) keyboardWillShow:(NSNotification *)notification {

    //获取键盘高度,在不同设备上,以及中英文下是不同的

    CGPoint keyBoardPoint =  [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin;

// 经过测试使用键盘起点坐标y值不用键盘高度计算效率更高,更加流畅。

    if (keyBoardPoint.y <= 0) {

        return;

    }

// _registerProtocolButton 为最底部不想被遮挡的控件

    // 通过 offset +  tempY = _registerProtocolButton.psk_top

    // tempY + _registerProtocolButton.psk_height = keyBoardPoint.y

    // 最终推出结果而 64的偏差值是因为 两者的坐标系起点相差一个导航栏高度

    CGFloat offset = _registerProtocolButton.psk_top - keyBoardPoint.y + _registerProtocolButton.psk_height + 64;

    if (offset > 0) {

         double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

        [UIView animateWithDuration:duration animations:^{

            [self.mainView mas_remakeConstraints:^(MASConstraintMaker *make) {

                make.top.equalTo(self.naviView.mas_bottom).offset(-offset);

            }];

        }];

    }

}

///键盘消失事件

- (void) keyboardWillHide:(NSNotification *)notify {

    // 键盘动画时间

    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    //视图下沉恢复原状

    [UIView animateWithDuration:duration animations:^{

        [self.mainView mas_remakeConstraints:^(MASConstraintMaker *make) {

            make.top.equalTo(self.naviView.mas_bottom).offset(0);

        }];

    }];

}


猜你喜欢

转载自blog.csdn.net/calvin_cn/article/details/59528400