Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Swift - continuing animation after returning to view

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)
    }
like image 269
Jordy Avatar asked Feb 02 '26 00:02

Jordy


1 Answers

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
}
like image 130
clemens Avatar answered Feb 03 '26 16:02

clemens