iOS 監聽鍵盤

cyjjkz1 8年前發布 | 2K 次閱讀 Objective-C IOS

百度所查到的鍵盤監聽大部分用的是

UIKeyboardDidShowNotification//已經顯示

UIKeyboardDidHideNotification//已經隱藏

然后我自己去試一直覺得一些空間跟隨鍵盤的移動是有時間間隔的  一直想不明白他們是怎么實現的  求大神告知  所以自己看源碼發現還有

UIKeyboardWillShowNotification//將要顯示

UIKeyboardDidHideNotification//將要隱藏

這樣是能完美的解決問題的  至少在我自己的項目需求中是可以的

最后別忘記在控制器消失中移除觀察者哦


- (void) registerForKeyboardNotifications{

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

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

}

//鍵盤顯示注冊通知

- (void) keyboardWasShown:(NSNotification *) note{


    // 獲取位置和大小

    CGRect keyboardBounds;

    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];

    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    

    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];

    

    // 獲取位置和大小

    CGRect containerFrame = _menuView.frame;

    // 計算出y坐標

    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);

    _mnueHeight = containerFrame.origin.y;

    _maxHeight = containerFrame.origin.y;

    // 動畫改變位置

    [UIView animateWithDuration:[duration doubleValue] animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationDuration:0.1];

        [UIView setAnimationCurve:[curve intValue]];

        // 更改位置

        _menuView.frame = containerFrame;

    }];

}

//鍵盤消失通知

- (void) keyboardWasHidden:(NSNotification *) note{

    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    

    // 獲取位置和大小

    CGRect containerFrame = _menuView.frame;

    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;

    

    // 動畫改變位置

    [UIView animateWithDuration:[duration doubleValue] animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationDuration:[duration doubleValue]];

        [UIView setAnimationCurve:[curve intValue]];

        // 更改位置

        _menuView.frame = containerFrame;

    }];

}


 本文由用戶 cyjjkz1 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!