当键盘出现时,将UITextField和UITableView向上移动

Spe*_*efy 1 objective-c uinavigationbar uitableview uitextfield ios

我有一个视图1.导航栏2.UITableView 3. UITextView.

当我开始编辑textView时,会出现一个键盘,我需要为TextView和TableView设置动画.我已经实现了:https://stackoverflow.com/a/8704371/1808179,但这会动画整个视图,覆盖导航栏.

我尝试单独动画textView,如:

- (void)keyboardWillShow:(NSNotification*)notification
{
    CGRect chatTextFieldFrame = CGRectMake(chatTextField.frame.origin.x,chatTextField.frame.origin.y-218,chatTextField.frame.size.width,chatTextField.frame.size.height);
    [UIView animateWithDuration:0.5 animations:^{ chatTextField.frame = chatTextFieldFrame;}];
}
Run Code Online (Sandbox Code Playgroud)

但它没有动画,也不会与TableView同步动画.

在不覆盖导航栏的情况下,为tableView和textView设置动画的最佳方法是什么?

pet*_*are 7

在解决这个问题时,我通常会使用以下代码段.

使用UITableView(它只是UIScrollView的子类),您应该设置,contentInsets而不是每次只更改框架.在具有半透明键盘的iOS7中,这一点特别好.

- (void)viewDidLoad;
{
    [super viewDidLoad];

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

- (void)dealloc;
{
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification;
{
  NSDictionary *userInfo = [notification userInfo];
  NSValue *keyboardBoundsValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
  CGFloat keyboardHeight = [keyboardBoundsValue CGRectValue].size.height;

  CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  UIEdgeInsets insets = [[self tableView] contentInset];
  [UIView animateWithDuration:duration delay:0. options:animationCurve animations:^{
    [[self tableView] setContentInset:UIEdgeInsetsMake(insets.top, insets.left, keyboardHeight, insets.right)];
    [[self view] layoutIfNeeded];
  } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification;
{
  NSDictionary *userInfo = [notification userInfo];
  CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  UIEdgeInsets insets = [[self tableView] contentInset];
  [UIView animateWithDuration:duration delay:0. options:animationCurve animations:^{
    [[self tableView] setContentInset:UIEdgeInsetsMake(insets.top, insets.left, 0., insets.right)];
    [[self view] layoutIfNeeded];
  } completion:nil];
}
Run Code Online (Sandbox Code Playgroud)