0
votes

I'm trying to animate the scaling of an UIButton but am having difficulties getting it to animate the way I want it to.

I have a UIButton set up with a stretchable UIImage. I want its height to scale to a certain size and give it the effect that it is 'growing'. I use the code below, but it animates the UIButton growing from top and bottom, rather than just bottom. See the code here:

myButton.transform = CGAffineTransformMakeScale(1,0.5);
myButton.alpha = 0.6f;  
[UIView beginAnimations:@"myButton" context:nil];
[UIView setAnimationDuration:0.5];
myButton.transform = CGAffineTransformMakeScale(1,1);
myButton.alpha = 1.0f;
[UIView commitAnimations];

It's hard to explain, basically I want the UIButton to grow from only one side (the bottom) rather than it grow by expanding both sides. Any suggestions?


UPDATE

I also tried changing the button's frame and that did not work either. This time, no animation was seen at all. This is my code:

CGRect  buttonRect = CGRectMake(0, 0, 150, 22);
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = buttonRect;

myButton.alpha = 0.6f;
[self.view addSubview:myButton];

[UIView beginAnimations:@"myButton" context:nil];
[UIView setAnimationDuration:0.3];  
CGRect buttonRect2 = CGRectMake(0, 0, 150, 52);
myButton.frame = buttonRect2;
myButton.alpha = 1.0f;
[UIView commitAnimations];

Any ideas why it is not animating at all? I'm assuming it has something to do with how I'm setting the frame?

3

3 Answers

2
votes

You won't see any animations until you call the setFrame: method..

CGRect  buttonRect = CGRectMake(0, 0, 150, 22);
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = buttonRect;

myButton.alpha = 0.6f;
[self.view addSubview:myButton];

[UIView beginAnimations:@"myButton" context:nil];
[UIView setAnimationDuration:0.3];  
CGRect buttonRect2 = CGRectMake(0, 0, 150, 52);
[UIView commitAnimations];

[UIView beginAnimations:@"myButton" context:nil];
[UIView setAnimationDuration:0.3];
 myButton.alpha = 1.0f;
[myButton setFrame: buttonRect2];
[UIView commitAnimations];
1
votes

The easiest way is probably to animate a change to the frame property, and increase the width and height there, rather than try to work out the complexities of a transformation based around the center point. If you really have a need for transforms on this view, you can always transparently update it once the animation has completed.

0
votes

I've answered my own question. You need to call layoutSubviews. See here:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, 150, 22);

myButton.alpha = 0.6f;
[self.view addSubview:myButton];
[myButton layoutSubviews];

[UIView beginAnimations:@"myButton" context:nil];
[UIView setAnimationDuration:0.3];  
myButton.alpha = 1.0f;
myButton.frame = CGRectMake(0, 0, 150, 52);
[myButton layoutSubviews];
[UIView commitAnimations];