0

I recently had to turn on Auto Layout for the storyboard in my project. This affected a view that I hoped it would not. The view I am describing has many UILabels and they are positioned programmatically based on whether there is an image present in the view. However, now my programmatic positioning code does nothing, and the labels stay where they were placed on the view in the storyboard regardless. To get around this, I tried an animation in viewDidLoad, which did nothing:

[UIView animateWithDuration:0.5 animations:^{

            label1.frame = CGRectMake(10, baseY, 300, 50);
            label2.frame = CGRectMake(10, baseY+35, 300, 50);
            label3.frame = CGRectMake(10, baseY+60, 300, 50);
            label4.frame = CGRectMake(10, baseY+85, 300, 50);
            label5.frame = CGRectMake(10, baseY+110, 300, 50);
            label6.frame = CGRectMake(10, baseY+135, 300, 50);
            label7.frame = CGRectMake(10, baseY+180, 300, 175);
}];

Is there a way that I can programmatically reposition my labels without interfering with Auto Layout?

Andrew
  • 479
  • 1
  • 5
  • 13

1 Answers1

2

You need to animate the constraints rather than the frame. If you don't, then auto layout will reposition the views right back where they were before; that is its job, after all.

(But there is no point animating in viewDidLoad; the view is not in the interface yet, so there is nothing to animate.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Here's my explanation of the relationship between animation and auto layout: http://www.apeth.com/iOSBook/ch17.html#_animation_and_autolayout – matt Jul 26 '14 at 03:46
  • And see my essay here: http://stackoverflow.com/questions/12943107/how-do-i-adjust-the-anchor-point-of-a-calayer-when-auto-layout-is-being-used/14105757#14105757 – matt Jul 26 '14 at 03:47
  • There aren't any constraints in the particular view I am working in. – Andrew Jul 27 '14 at 16:44
  • Yes there are. Once you are in a nib/storyboard that uses auto layout, everything in it has constraints. The storyboard generates the constraints implicitly for you if you don't specify them yourself. See my (slightly outdated) discussion here: http://www.apeth.com/iOSBook/ch14.html#_constraints_in_the_nib – matt Jul 27 '14 at 16:47
  • Thus you have left yourself in a kind of hybrid situation, because you have not taken control of the layout; you would be much better off using explicit constraints for _everything_, which you can change in real time to reposition your views. – matt Jul 27 '14 at 16:48