简体   繁体   中英

How do I animate a UIButton between two PNG images?

I have two PNGs I want to use as a button. How can I animate a UIButton by switching rapidly between these two images?

You can use animationImages property of your button's imageView :

myButton.imageView.animationImages =
[NSArray arrayWithObjects:[UIImage imageNamed:@"image1.png"],
                          [UIImage imageNamed:@"image2.png"],
                          nil];
myButton.imageView.animationDuration = 0.5; //whatever you want (in seconds)
[myButton.imageView startAnimating];

Your button will switch between your two images.

EDIT: As @tidbeck pointed the button needs to have an image assigned to create the imageview property.

Normally for a button you can set three "live" states: - Normal - Highlighted - Selected I don't know if this can help, but if you set one image to "Normal" and the other image to "Highlighted" you can see the two images while pushing the button. I don't know if this effect is enough for you.

This small example shows how to set a UIButton to show an indefinite animation of a heart beating.

private func showHeartedAnimation() {
    var images = [UIImage]()
    for i in 1...8 { images.append(UIImage(named: "heart\(i)")!) }
    self.heartButton.setImage(UIImage.animatedImage(with: images, duration: 0.2), for: .normal)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM