views:

51

answers:

1

I have a few buttons I would like to animate.

I have looked at and tried the animateWithDuration method but that seems to be for Views and I couldnt get my implementation to work.

Can this method work for animating buttons too? if not how could it be done?

EDIT I have the following code

-(void) animate:(UIButton*) b withMonster: (int) monster withState: (int) state andLastState:(int) last_state {
if (state < last_state) {
    float duration = 1.0 / 10;
    __block int stateTemp = state;
    [b animateWithDuration: duration
                animations: ^{ [UIImage imageNamed:[NSString stringWithFormat:@"m%d.a000%d.png", monster, state]]; }
                completion: ^{ [self animate: A1 withMonster: monster withState: stateTemp++ andLastState: last_state];; }];


}

and I call it like so

[self animate: A1 withMonster: monsterDecider withState: 1 andLastState: 5];

When this code executes the app crashes.

Is it correct to call is with self in both calls(self being ViewController).

Thanks

+1  A: 

You can animate buttons, yes. In the animations block you need to change some of the button parameters like this:

[UIView animateWithDuration:animTime
                 animations:^{button.frame = newFrame;}];

Looking at your code you probably want to set the button.imageView.image property to a new image (your code currently loads a new image but doesn't set it onto the button).

However, UIImageView objects actually support changing between multiple images without needing to use the UIView animateWithduration:... methods.

You probably want to set the following properties:

button.imageView.animationImages
button.imageView.animationDuration
button.imageView.animationRepeatCount

Then call

[button.imageView startAnimating];

and the UIImageView will do all the animation for you. See the docs on UIImageView: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImageView_Class/Reference/Reference.html

jhabbott
does it block the main thread?
alJaree
No, and you should be sure to call all UI-related methods from the main thread.
jhabbott
I have a NSTimer which runs and each execution it runs a switch statement, then depending on the case it animates a certain button. I tried the method you said and get the following crash error. -[NSCFString _contentStretch]
alJaree