Search code examples
iosobjective-cuiviewanimationnslayoutconstraint

Animate a view (button) with the keyboard showing


I have a button at the bottom of my main view and I want to animate it up with the keyboard when it is showing.

My button is set like this with a constraint in my storyboard :

enter image description here

I have linked the constraint in the code:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myConstraint;

Added a notification when keyboard is showing:

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

And here is the keyboardWillShow implementation:

- (void)keyboardWillShow: (NSNotification *)notification {
    NSDictionary *dictionary = notification.userInfo;
    CGRect keyboardFrame = [dictionary[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    [UIView animateWithDuration:1.0f animations:^{
        self.myConstraint.constant = keyboardFrame.size.height + 18;
    }];
}

Although it works, the button doesn't animate but instead is immediately set at its new location on the view. I tried to add a completion block to see what happens, and actually the completion is immediately called instead of waiting a second as it should...

What is wrong? Thanks for your help.


Solution

  • The thing that requires animation is the layout triggered by the constraint change....

    self.myConstraint.constant = keyboardFrame.size.height + 18;
    [self.view setNeedsUpdateConstraints];
    
    [UIView animateWithDuration:1.0f animations:^{
       [self.view layoutIfNeeded];
    }];