Search code examples
iosios6core-animationautolayout

iOS 6 animate size of view and have constraints move other views


I'm playing with iOS 6 autolayout for the first time and I'm trying to figure out how to mix autolayout and animation.

I've got container view, ViewA, which is a certain height. I've got a UIDatePicker, ViewB, which is 216 tall and has a constraint that sets the vertical space between ViewA and ViewB = 0, so that ViewB is essentially pinned to the bottom of ViewA.

enter image description here

I want to animate ViewA's height to make it smaller and have ViewB remain pegged to the bottom of ViewA the entire time.

[UIView animateWithDuration:2.0 animations:^{
    CGRect containerFrame = self.tableContainerView.frame;
    containerFrame.size.height -= self.datePicker.frame.size.height;
    self.tableContainerView.frame = containerFrame;

} completion:^(BOOL finished) {
    NSLog(@"Done");
}];

ViewA, the container view, does get shorter as intended, but ViewB does not follow along.

How can I get the constraints between ViewA and ViewB to automatically adjust ViewB's position during the animation?


Solution

  • It looks like from your constraints, that it should work. The problem might be the way you do the animation. You should do that with constraints, not frames. If viewA has a constraint to the bottom of the superview, then you can just animate the constant of that constraint. Make an IBOutlet to that bottom constraint, and do this (bottomCon is the outlet in my example):

    self.bottomCon.constant = self.datePicker.bounds.size.height;
    [UIView animateWithDuration:2.0 animations:^{
        [self.view layoutSubviews];
        [self.containerView layoutSubviews]; 
    } completion:^(BOOL finished) {
        NSLog(@"Done");
    }];
    

    In my edit, I also added the [self.containerView layoutSubviews] line. This is necessary so that its subviews are updated properly too (otherwise they just jump to the new location).