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.
I have added 8 images into the Assets.xcassets, and named them like this: heart1
, heart2
, ..., heart8
.
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)
}
If you want to disable the animation at some point, just assign a simple UIImage to the same button.
精彩评论