我需要无限旋转视图,直到被告知停止

时间:2017-04-25 11:14:19

标签: ios swift animation uiview rotation

有很多与此类似的帖子,我看过,但没有一个有效。

到目前为止,这是我的代码。

func startRotating(view : UIImageView, rotating : Bool) {

    //Rotating the rotatingClockBarImage
    UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], animations: {

        view.transform = CGAffineTransform(rotationAngle: CGFloat.pi)

    }, completion: {finished in

        UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], animations: {

            view.transform = CGAffineTransform(rotationAngle: 0)

        }, completion: nil)
    })//End of rotation

    continueRotating(view: view)

}

最初的问题是我无法旋转360度。我想通过中途旋转,另一半完成。

现在的问题是这个动画一旦完成,那就是它。我试过把它放在while循环中,for循环,来回调用两个类似的函数。没有什么可行的,只是一直冻结我的应用程序。

在for循环中,例如,运行3次,我放了一个print()。打印件向控制台写入三次,但动画只发生一次。正因为如此,我认为动画在它开始之前就会自行消失,而最终的旋转是唯一可以完成的动作。所以我需要找到一种方法来让它通过每个旋转。

在游戏应用程序的Xcode中,以前的Xcode版本让他们的飞机轻松旋转,这一点并不难。我试图避免删除并重新安装旧版本,以便我可以查看该代码。

2 个答案:

答案 0 :(得分:4)

实际上它会更容易:

   extension UIView {
    func rotate360Degrees(duration: CFTimeInterval = 1.0) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat.pi * 2
        rotateAnimation.duration = duration
        rotateAnimation.repeatCount = Float.infinity
        self.layer.add(rotateAnimation, forKey: nil)
    }

    func stopRotating(){
        self.layer.sublayers?.removeAll()
        //or
        self.layer.removeAllAnimations()
    }
}

然后旋转: yourView.rotate360Degrees()

停止: yourView。 stopRotating()

答案 1 :(得分:-1)

你是否尝试在下半圈完成时再次调用startRotating?

请注意,如果您希望它停止,您应该使用自己的“停止”标志有条件地执行此操作。

相关问题