iOS移动开发中监听键盘移动的事件,自动调整view-(1)-UIKeyboardFrameEndUserInfoKey

来源:互联网 发布:阿里云域名可以转让吗 编辑:程序博客网 时间:2024/05/16 07:36

UIKeyboardFrameEndUserInfoKey 是监听键盘的移动的时间,比如说键盘推出、键盘回收。
可在iOS程序中通过C语言私有的内联函数实现

//通过监听键盘的动作,得到键盘的高度

static inline CGFloat getKeyboardHeight(NSNotification *notify) {

    CGRect kbSize = [[notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    return kbSize.size.height;

}

(static 私有 inline内联函数===》内联函数相当于define,在函数中调用的时间,直接复制获取,减少了调用的时间提高了效率)

//键盘将要显示时候

- (void) keyboardWillShow:(NSNotification *)notify {
    UIView *sv = focusTextField.superview;
    CGFloat kbHeight = getKeyboardHeight(notify);
    // 取得键盘的动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat screenHeight = self.view.bounds.size.height;
    CGFloat viewBottom = sv.frame.origin.y + sv.frame.size.height;
    if (viewBottom + kbHeight < screenHeight) return;
    
    // 键盘会盖住输入框, 要移动整个view了
    delta = viewBottom + kbHeight - screenHeight + 50;
    
    // masonry的地方了 mas_updateConstraints 更新superView的约束(masonry是自动布局的三方库,可参考github)
    [superView mas_updateConstraints:^(MASConstraintMaker *make) {

        //调整上面的偏移量
        make.top.equalTo(self.view.mas_top).offset(-delta);
    }];

    [UIView animateWithDuration:duration animations:^void(void){
        // superView来重新布局
        [superView layoutIfNeeded];
    }];

}

//键盘将要隐藏的时候
- (void) keyboardWillHidden:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [superView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
    }];
    [UIView animateWithDuration:duration animations:^{
        [superView layoutIfNeeded];
    }];
    delta = 0.0f;
}



0 0
原创粉丝点击