iOS监听键盘上升和降落

很多时候,我们用到输入框都需要监听键盘上升和下降,以便让用户可以看到自己输入的文字。

实现方法很简单,代码如下:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

#pragma mark 监听键盘的显示与隐藏

///键盘显示事件

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

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

    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    

    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)

    CGFloat offset = (self.textView.frame.origin.y+self.textView.frame.size.height) - ([UIScreen mainScreen].bounds.size.height - kbHeight);

    

    // 取得键盘的动画时间,这样可以在视图上移的时候更连贯

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

    

    //将视图上移计算好的偏移

    if(offset > 0) {

        [UIView animateWithDuration:duration animations:^{

            self.frame = CGRectMake(self.frame.origin.x, -offset, self.frame.size.width, self.frame.size.height);

        }];

    }

}


///键盘消失事件

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

    // 键盘动画时间

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

    

    //视图下沉恢复原状

    [UIView animateWithDuration:duration animations:^{

        self.frame = oldFrame;

    }];

}

一切都很顺利吧!这里有一个小坑存在,在此我做一下解释。

        第一、self.frame = oldFrame;这个最好是把你要上下移动的控件的原先位置,作为变量存储起来,方便使用些。

第二、

    CGFloat offset = (self.textView.frame.origin.y+self.textView.frame.size.height) - ([UIScreen mainScreen].bounds.size.height - kbHeight);

这行代码的主要意思就是用输入框的bottom的y座标——整个屏幕与键盘的高度差。

很多时候这个监听在自定义控件里面的时候,我们算出来的不是整个屏幕与键盘的高度差,而是这个控件和键盘的高度差,很容易就导致键盘上升时候,输入框的位置不够精确。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章