Xcode Swift - 返回视图后继续动画

时间:2017-05-16 02:06:49

标签: ios swift xcode animation swift3

标题可能有点模棱两可,所以我会直截了当。在我的Xcode项目中,我在我的初始ViewController中实现了一个简单的动画,它运行正常,但在离开初始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 个答案:

答案 0 :(得分:2)

您应该将云的位置重置为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
}