开发者

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

开发者 https://www.devze.com 2023-01-25 04:47 出处:网络
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 pres

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 c开发者_运维知识库enter 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!


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];


Just to add to this, if your UIButton has an image, then you also need to set the autoresizingMask property of the button's imageView. In this example, both for height and width.

myButton.titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

myButton.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

Also, as a side note, [UIView animateWithDuration... is way better than [UIView beginAnimations...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号