Search code examples
swiftanimationuiimageview

how to do imageView.startAnimating() with completion in swift?


I would like a simple image array animation to run when a button is clicked. The below code works well, but I would like the last image in the array to be set as the imageview image after. How would I change the image on completion instead of it going back to the original?

let imageArray = [UIImage(named: "Frog-1.gif")!, UIImage(named: "Frog-2.gif")!, UIImage(named: "Frog-3.gif")!, UIImage(named: "Frog-4.gif")!]

@IBOutlet var imageView1: UIImageView!

@IBAction func button1(sender: UIButton) {

    imageView1.animationImages = imageArray
    imageView1.animationDuration = 1.0
    imageView1.animationRepeatCount = 1
    imageView1.startAnimating()

}

Solution

  • Add #selector() and @objc at last solution.

    When the button is pressed you can call a function with a delay:

    self.perform(#selector(afterAnimation), with: nil, afterDelay: imageView1.animationDuration)

    Then stop the animation and add the last image of imageArray to the imageView in the afterAnimation function:

    @objc func afterAnimation() {
        imageView1.stopAnimating()
        imageView1.image = imageArray.last
    }