3

Title might be a bit ambiguous so i'll get straight to the point. Within my Xcode project I've implemented a simple animation in my initial ViewController, which functions fine, but after leaving the initial View, and moving to another scene, and then returning to the initial view, the animation fails to restart and I can't figure out why.

Here's the relevant code from my initial view

     override func viewDidAppear(_ animated: Bool) {
     super.viewDidAppear(animated)

        //cloud animation
        let oldCenter = cloud.center
        let newCenter = CGPoint(x: oldCenter.x - 800, y: oldCenter.y)
        UIView.animate(withDuration: 30.0, delay: 0.0, options:
            [.curveLinear, .repeat], animations: {
                self.cloud.center = newCenter
        }, completion: nil)
        //second cloud animation
        let oldCenter2 = cloud2.center
        let newCenter2 = CGPoint(x: oldCenter2.x + 800, y: oldCenter2.y)
        UIView.animate(withDuration: 15.0, delay: 0.0, options:
            [.curveLinear, .repeat], animations: {
                self.cloud2.center = newCenter2
        }, completion: nil)

    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }

1 Answer 1

2

You should reset positions of the clouds to their original centers in viewDidDisappear:

var originalCenter: CGPoint!
var originalCenter2: CGPoint!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    originalCenter = cloud.center
    originalCenter2 = cloud2.center
    ...
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    // restore positions
    cloud.center = originalCenter
    cloud2.center = originalCenter2
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.