Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autolayout breaks UIView Animation

Struggling to make my app work on both the iPhone 5 and the smaller iPhone's prior. Would be happy to require iOS6 and use Autolayout because that works great.

However, the app has 4 buttons that regularly swap positions, so I assign each button a different location from an array and then animate the movement with something like this:

[UIView animateWithDuration:0.5 animations:^{
    button1.center = [[locations objectAtIndex:0] CGPointValue];
    button2.center = [[locations objectAtIndex:1] CGPointValue];
    button3.center = [[locations objectAtIndex:2] CGPointValue];
    button4.center = [[locations objectAtIndex:3] CGPointValue];
}];

This doesn't work with Autolayout. Nothing changes. The best I've gotten is that it will animate to a position then immediately snap back.

When I remove Autolayout however all the buttons are scrunched up on the smaller iPhones, and because I'm using points set by the iPhone 5 size they end up lower down, putting the bottom row off the screen. I original had different CGPoint numbers that I got from Interface Builder, but they were "wrong", though I'm thinking they were "wrong" because they were the numbers for Autolayout to use. The array just so you can see:

buttonLocations = [NSArray arrayWithObjects:
        [NSValue valueWithCGPoint:CGPointMake(57, 523)],
        [NSValue valueWithCGPoint:CGPointMake(109, 523)],
        [NSValue valueWithCGPoint:CGPointMake(57, 471)],
        [NSValue valueWithCGPoint:CGPointMake(109, 471)],
        nil];

What should I do to fix this problem? Setting different points for each sized device doesn't seem very efficient.

like image 916
William Robinson Avatar asked Dec 14 '12 17:12

William Robinson


1 Answers

The solution is that you animate the items transform property, not its position.

The position is going to be set by autolayout and you don't want to fight it. The actual position on the screen, though, is going to be its "correct" (set by auto layout) position, offset by its transform property.

So you can say button.transform = CGTransformMake(x,y) and it will appear x and y off from it's center position.

There are a variety of CGWhatever macros to make these transforms easily, and you can just change them in an animation block to move the items around.

like image 84
nirvana Avatar answered Sep 19 '22 23:09

nirvana