Matt Parkins
Matt Parkins

Reputation: 24688

iOS Animating main UIViewController's View height

I have a text field pinned to the bottom of my main UIViewController's view (self.view), and when the user clicks on it this function is called (via a UIKeyboardWillShowNotification) which will alter the height of the self.view.frame:

-(void)keyboardWillShow: (NSNotification*) notification {
    NSDictionary* info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGFloat textFieldHeight = activeField.frame.size.height;
    CGPoint textFieldOrigin = activeField.frame.origin;
    textFieldOrigin.y += textFieldHeight;

    CGRect visibleRect = self.view.frame;
    visibleRect.size.height -= keyboardSize.height;

    if (!CGRectContainsPoint(visibleRect, textFieldOrigin)) {
        CGRect r = self.view.frame;
        r.size.height -= keyboardSize.height;

        [UIView animateWithDuration:1.0
                     animations:^{
                         self.view.frame = r;
                     }];
    }
}

It resizes the self.view.frame fine, so it is all being called and run, but for some reason refuses to animate it over a second - it just appears in place immediately.

What do I need to do in order to animate this change in height?

Upvotes: 1

Views: 198

Answers (2)

Eli Waxman
Eli Waxman

Reputation: 2897

If you have auto layout on you shouldn't change the frame directly, instead you should change on of the constrains. Add an IBOutlet to the constrain (the bottom constrain), and change the constant like so:

myTextFieldConstrain.constant -= YOUR_VALUE

Also, if you want it to animate, call [YOURSUPERVIEW layoutIfNeeded]; after you change the constant.

Example:

[UIView animateWithDuration:1.0
                     animations:^{
                         myTextFieldConstrain.constant -= YOUR_VALUE;
                         [YOURSUPERVIEW layoutIfNeeded];
                     }];

Upvotes: 1

Nicola Miotto
Nicola Miotto

Reputation: 3696

Try to dispatch it with a slight delay, like:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  [UIView animateWithDuration:1.0
                     animations:^{
                         self.view.frame = r;
                     }];
}

It usually makes the trick.

Upvotes: 1

Related Questions