Rutger Huijsmans
Rutger Huijsmans

Reputation: 2408

UIButton Animation in Swift

I'm trying to make an animation on a button upon button press. The case is the following. The button will have have a picture of an apple. When pressed it will change to image1, image2, image3 (like a .gif) and then it will be a picture of a pear. Right now I'm just seeing it change from an apple to a pear and skipping over the animation that I'm trying to create.

This is the code for the animation part:

    var image1:UIImage = UIImage(named: buttonAnimationImage1)!;
    var image2:UIImage = UIImage(named: buttonAnimationImage2)!;
    var image3:UIImage = UIImage(named: buttonAnimationImage3)!;

    sender.imageView!.animationImages = [image1, image2, image3];
    sender.imageView!.animationDuration = 1.5;
    sender.imageView!.startAnimating();

Upvotes: 0

Views: 2051

Answers (1)

Reynaldo Aguilar
Reynaldo Aguilar

Reputation: 1936

You can have this behavior using animated images.

var image1:UIImage = UIImage(named: buttonAnimationImage1)!;
var image2:UIImage = UIImage(named: buttonAnimationImage2)!;
var image3:UIImage = UIImage(named: buttonAnimationImage3)!;
var images = [image1, image2, image3]
var animatedImage = UIImage.animatedImageWithImages(images, duration: 1.5)
sender.setImage(animatedImage, forState: UIControlState.Normal)

The only problem up to here is that the animation will continue forever. What is more, you can't say to the animated images the number of times that the animation will be running. So, in order to stop the animation, after the required time you will need to change the image of the button again and set it the pear image.

The complete source code is:

// setting the images that conform the animation
var image1:UIImage = UIImage(named: buttonAnimationImage1)!;
var image2:UIImage = UIImage(named: buttonAnimationImage2)!;
var image3:UIImage = UIImage(named: buttonAnimationImage3)!;
var images = [image1, image2, image3]
var animatedImage = UIImage.animatedImageWithImages(images, duration: 1.5)
sender.setImage(animatedImage, forState: UIControlState.Normal)

// code for setting the pear image to the button after a delay
let delay = 1.3 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {  
    sender.setImage(pearImage, forState: .Normal) 
}

Upvotes: 6

Related Questions