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座標——整個屏幕與鍵盤的高度差。

很多時候這個監聽在自定義控件裏面的時候,我們算出來的不是整個屏幕與鍵盤的高度差,而是這個控件和鍵盤的高度差,很容易就導致鍵盤上升時候,輸入框的位置不夠精確。




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