Search code examples
iosuitableviewcore-animationuitextfielduitextfielddelegate

Synchronously slide up UIView and resize UITableView when UITextField is fired


I would to resize a UITableView and slide up a UIView that contains a UITextField when this field is fired. These are two simple mockups:

enter image description here enter image description here

Now I have this code:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationBeginsFromCurrentState:YES];

    [myView setFrame:CGRectMake(myView.frame.origin.x, myView.frame.origin.y - 167, myView.frame.size.width, myView.frame.size.height)]; // 216 (keyboard's height) - 49 (tabbar's height) = 167

    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationBeginsFromCurrentState:YES];

    [myView setFrame:CGRectMake(myView.frame.origin.x, myView.frame.origin.y + 167, myView.frame.size.width, myView.frame.size.height)];

    [UIView commitAnimations];
    return TRUE;
}

The problem is that the keyboard slide up animation and the myView slide up animation are not synchronous. How to make these two animation perfectly synchronous?

And how to resize the UITableView when the keyboard is visible and return to the original height when keyboard will hide?


Solution

  • The short answer is that you need to subscribe to UIKeyboardWillShowNotification and UIKeyboardWillHideNotification. Those notifications contain the exact parameters of the keyboard animation.

    The long answer is https://stackoverflow.com/a/8704371/77567.

    Regarding your tab bar: the answer I linked assumes you want to slide your view down to the bottom edge of the screen when the keyboard is dismissed. Since you want to slide it down to the edge of the tab bar, you need to look at whether the keyboard is hiding or showing (by checking note.name). If it's showing, you should save the current frame of the view in an instance variable. If it's hiding, you should set the view's new frame to that frame you saved in an instance variable, instead of setting it based on the keyboard's end frame.