Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate a view containing subviews with autolayout

This is the setup:

  • A UIView created on Interface Builder, linked to an IBOutlet variable (_vAbout)
  • A constraint for this view that we want to animate, linked to an IBOutlet variable (_ctrBottomAboutView)

I am using this code to animate:

_ctrBottomAboutView.constant = -100;
[UIView animateWithDuration:0.5 animations:^{
    [_vAbout layoutIfNeeded];
}

My problem is: whenever the view has any subviews in it, the animation doesn't work. However, if the view has no children, the animation works correctly.

Do you have any idea of a solution? I have tried everything: adding and removing constraints instead of modificating the constant value, adding constraints to the subviews on Interface Builder...

like image 542
Javier Chávarri Avatar asked Oct 14 '13 11:10

Javier Chávarri


1 Answers

After some experiments starting from the ground with an empty project, this is what I've found:

Given A the view we want to animate and B its superview

  • It's very important to keep in mind that the view that receives the layoutIfNeeded message is the view that owns the constraint.
  • In the case of NSLayoutAttributeWidth and NSLayoutAttributeHeight the owner of the constraint is actually A, but in all the other cases, the view that owns the constraint is B

HOWEVER

  • If A does not have any subviews, we can call [A layoutIfNeeded] at any time on our code and it will work
  • If A has one or more subviews but we start the animation on viewDidLoad we can call [A layoutIfNeeded] and it will work
like image 152
Javier Chávarri Avatar answered Oct 14 '22 06:10

Javier Chávarri