且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在键盘出现时滚动表格,以适应输入框的显示

更新时间:2022-08-15 14:03:22

//
- (void)registerForKeyboardNotifications {
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(keyboardWillShow:)
                                               name:UIKeyboardWillShowNotification
                                             object:nil];
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(keyboardWillHide:)
                                               name:UIKeyboardWillHideNotification
                                             object:nil];
  return;
}

- (void)keyboardWillShow:(NSNotification *) notif {
  NSDictionary *info = [notif userInfo];
  NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
  CGSize keyboardSize = [value CGRectValue].size;
  [_tableView setContentOffset:CGPointMake(_tableView.contentOffset.x,
                                           _tableView.contentOffset.y + keyboardSize.height + 10)
                      animated:YES];
  return;
}

- (void)keyboardWillHide:(NSNotification *) notif {
  NSDictionary *info = [notif userInfo];
  NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
  CGSize keyboardSize = [value CGRectValue].size;
  [_tableView setContentOffset:CGPointMake(_tableView.contentOffset.x,
                                           _tableView.contentOffset.y - keyboardSize.height - 10)
                      animated:YES];
  return;
}