1

I'm updating my iPhone app for the iPhone 5's larger screen, and there seems to be a problem with animateWithDuration:. Before I turned on autolayout, the interface elements would move slightly up the screen when the UITextField became first responder, and would move down back to their original positions when the UITextField lost its first responder status. Now, they just haphazardly fly up and off the screen, and I have no idea why. I move the objects with the code below (and this worked with autolayout turned off):

[UIView animateWithDuration:.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    int offset = 160;
    [object1 setFrame:CGRectMake(0, -offset, object1.frame.size.width, object1.frame.size.height)];
    [object2 setFrame:CGRectMake(object2.frame.origin.x, object2.frame.origin.y-offset, object2.frame.size.width, object2.frame.size.height)];
    [object3 setFrame:CGRectMake(object3.frame.origin.x, object3.frame.origin.y-offset, object3.frame.size.width, object3.frame.size.height)];
             }
                 completion:^(BOOL finished){}];

Does it have something to do with trying to move the objects by a constant? Even when I set offset to 0, all the objects still fly off the screen. I've tried detecting which screen the device has and moving the objects by different amounts, but that hasn't worked either. Does anybody have any ideas?

Thanks in advance!

The Awesome Guy
  • 322
  • 5
  • 15
  • 1
    autolayout and frame animation conflict with each other. I regard this as iOS 6's biggest blunder (of many). For solutions, see my book: http://www.apeth.com/iOSBook/ch17.html#_animation_and_autolayout – matt May 17 '13 at 19:50

1 Answers1

2

When using auto layout, unless these are objects that were manually added to the view with translatesAutoresizingMaskIntoConstraints = YES, autolayout will often thwart attempts to animate by changing the frame. If there is anything in place that will cause the constraints to be reapplied, the objects will move back to wherever the constraints dictate they should be, overriding your attempts to adjust their frame properties.

If animating the movement of objects like this while using autolayout, you would either (a) create an IBOutlet for their top constraint (if adjusting y; if adjusting x, too, you would use the leading constraint also) and then change that constraint's constant property and then call layoutIfNeeded from within the animation block; or (b) remove the constraints and create new ones. (I generally do the former.)

See the latter part of this answer for an example of how to create IBOutlet for constraint and then changing the constant property in animation block.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044