iosswiftxcodeanimationviewdidappear

problem with image animation in viewDidAppear(), any advice?


I am trying to create an animation that scrolls through a series of images. The following code does not have any animation and only the last image of the series appears on the screen. How do I fix this animation?

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        imageSelection(score: 50)
    }
func imageSelection(score: Int) {
        var myScore = score
        if score < 10 {
            myScore = 1
        }
        else if score < 20 && score > 10 {
            myScore = 2
        }
        else if score < 30 && score > 20 {
            myScore = 3
        }
        else if score < 40 && score > 30 {
            myScore = 4
        }
        else if score < 50 && score > 40 {
            myScore = 5
        }
        else if score == 50 {
            myScore = 6
        }
        for i in 1...myScore{
            UIView.animate(withDuration: 0.5) {
                self.cookieImage.image = UIImage(named: "rewardsCookie\(i)")
                self.view.layoutIfNeeded()
            }
        }
    }

Solution

  • As Matt said, you are not animating any animatable properties. You can achieve what you want to by using layer animations. Replace your for loop with the following code.

        var images = [CGImage]()
        for i in 1...myScore{
            images.append(UIImage(named: "rewardsCookie\(i)")!.cgImage!)
        }
        let animation = CAKeyframeAnimation(keyPath: "contents")
        animation.values = images
        let delay = 3.0 // in case you need to delay your animation
        animation.duration = 5.0 // change to the total duration (ex: 0.5 * myScore)
        animation.beginTime = CACurrentMediaTime() + delay
        self.cookieImage.layer.add(animation, forKey: nil)
    

    Note that for layer animations, you are not actually seeing the UIImageView, but a cached version of it. This is removed from the screen once the animation completes and the original layer shows itself again. So you will see the image that was visible on the cookieImageView before the animation began. In order to persist the last image, add the following line after the code above

        self.cookieImage.image = UIImage(named: "rewardsCookie\(myScore)")
    

    For more information go through Apple's Documentation.