Animating UIButton background image

2019-06-16 20:17发布

问题:

Is there a way to animate a UIButton background image view with a set of images?

I've managed to do so with the imageView property, but couldn't find an equivalent background property.

10x

回答1:

To change a buttons backround image, or text for that matter - you need to change it for the particular UIControlState... i.e Highlighted, Selected, Disabled

Use

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state

I'm not sure if you can animate them, I've never tried. If you can't animate them, then you could put a UIImageView behind a transparent button and animate the images in that instead - just a thought.



回答2:

Here's what I did (inside a UIButton subclass):

Set the button images, like regular:

[self setBackgroundImage:[[UIImage imageNamed:@"button"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)] forState:UIControlStateNormal];
[self setBackgroundImage:[[UIImage imageNamed:@"button_pressed"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)] forState:UIControlStateHighlighted];

Override highlighted:

- (void)setHighlighted:(BOOL)highlighted {
     [UIView transitionWithView:self duration:0.25 options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowAnimatedContent animations:^{
         [super setHighlighted:highlighted];
     } completion:nil]; 
}


回答3:

You can animate an UIButton the way you animate an UIImageView like this...

-(void) addAnimationToButton:(UIButton*) button{
    UIImageView* animationView = [button imageView];
    NSArray* animations=[NSArray arrayWithObjects:
                         [UIImage imageNamed:@"sprite1.png"],
                         [UIImage imageNamed:@"sprite2.png"],
                         [UIImage imageNamed:@"sprite2.png"],
                         //and so on if you need more
                         nil];
    CGFloat animationDuration = 2.0;
    [animationView setAnimationImages:animations];
    [animationView setAnimationDuration:animationDuration];
    [animationView setAnimationRepeatCount:0]; //0 is infinite
}

And you use it like this:

[self addAnimationToButton:yourButton];
[[yourButton imageView] startAnimating]; //or stopAnimating


回答4:

Yes it is possible. Use NSTimer ,

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:5.00 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];

then, method is as follows,

- (void)changeImage
 {

           static int counter = 0;

           if([bannerArray count] == counter)
            {
                   counter = 0;
            }
            [button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:bannerArray[counter]]]] forState:UIControlStateNormal];

          counter++;
}

It worked for me. But adding animation like flip etc need to figure out. Hope this also one way to help your need.