關於鍵盤出現與隱藏時調整UITextField的顯示位置問題
1、首先在ViewDidLoad裏麵添加注冊鍵盤隱藏與出現的通知:
///< 注冊通知,以便在鍵盤將要出現時,調整頁麵 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; ///< 注冊通知,以便在鍵盤將要隱藏時,恢複頁麵 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2、在viewWillDisappear裏移除對鍵盤隱藏與出現的通知:
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; /// 注意:在此處需要移除通知,否則容易照成崩潰 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; return; }
3、實現鍵盤出現、隱藏時的通知回調:
#pragma mark - UIKeyboardWillShowNotification 通知 - (void)onKeyboardWillShow:(NSNotification *)notification { CGRect frame = self.view.frame; if (frame.origin.y < 0) { return; } // 獲取鍵盤的高度 CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification]; frame.origin.y -= (keyboardHeight - 20); [UIView animateWithDuration:0.35 animations:^{ self.view.frame = frame; }]; return; } #pragma mark - UIKeyboardWillHideNotification 通知 - (void)onKeyboardWillHide:(NSNotification *)notification { CGRect frame = self.view.frame; if (frame.origin.y > 0) { return; } // 獲取鍵盤的高度 CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification]; frame.origin.y += (keyboardHeight - 20); [UIView animateWithDuration:0.35 animations:^{ self.view.frame = frame; }]; return; } /// 獲取鍵盤高度 - (CGFloat)keyboardHeightWithKeyboardNotification:(NSNotification *)notification { NSDictionary *info = notification.userInfo; NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyboardSize = [value CGRectValue].size; CGFloat keyboardHeight = keyboardSize.height; return keyboardHeight; }
最後更新:2017-04-03 08:26:18