Search code examples
iphoneobjective-ccocoa-touchuikitcore-animation

Animating a width change in a UIButton with a fixed center point


I've run into this problem a few times now, but I couldn't find an exact answer on it anywhere.

I want to animate a UIButton's change in width, similar the to effect in the App Store when you press the FREE button and it changes to INSTALL. After the touch, the button expands but doesn't move. In the app store, the button just expands to the left: I want my button to expand in both directions.

I've tried wrapping button.frame = ... or button.bounds = ... within a [UIView beginAnimations:context:] block, but that doesn't work, even when I set the center within the block as well. No matter what I do, the button just seems to animation to a new position and then snap to the new width. Am I missing something here?

As an addendum, googling around turns up tons of people with similar problems, and often they just abandon whatever animation they were trying to do, which seems odd to me. This should be an easy solution, right? :)

Thanks!


Solution

  • I've just tested this and it works perfectly:

    // Button setup (to keep text central during animation)
    button.titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // Animate
    [UIView beginAnimations:nil context:nil];
    CGRect old = button.frame;
    CGFloat diff = 60;
    button.frame = CGRectMake(old.origin.x-diff/2.0, old.origin.y, old.size.width+diff, old.size.height);
    [UIView commitAnimations];