在Swift中动画旋转图像

时间:2017-03-05 22:57:49

标签: ios swift image uiimageview

我有一个图像,如果按下按钮我想继续旋转,直到我调用动作停止旋转。我试过这些网站:https://www.andrewcbancroft.com/2014/10/15/rotate-animation-in-swift/我不得不让代表团有机会,当我试图改变它时崩溃了 当我调用动作时,https://bencoding.com/2015/07/27/spinning-uiimageview-using-swift/只是不旋转。谢谢。代码如下:

Andrewcbancroft.com:

    extension UIView {
    func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat(M_PI * 2.0)
        rotateAnimation.duration = duration

        if let delegate: AnyObject = completionDelegate {
            rotateAnimation.delegate = delegate //<- error "Cannot assign value of type 'AnyObject' to type 'CAAnimationDelegate?'"
        }
        self.layer.add(rotateAnimation, forKey: nil)
    }
}

尝试将委托转换为! CAAnimationDelegate将使应用程序崩溃并显示错误代码无法转换类型&#39; test.ViewController&#39; (0x1074a0a60)到&#39; CAAnimationDelegate&#39; (0x10cede480)尝试旋转图像时。

Bending.com:

extension UIView {
    func startRotating(duration: Double = 1) {
        let kAnimationKey = "rotation"

        if self.layer.animation(forKey: kAnimationKey) == nil {
            let animate = CABasicAnimation(keyPath: "transform.rotation")
            animate.duration = duration
            animate.repeatCount = Float.infinity
            animate.fromValue = 0.0
            animate.toValue = Float(M_PI * 2.0)
            self.layer.add(animate, forKey: kAnimationKey)
        }
    }
    func stopRotating() {
        let kAnimationKey = "rotation"

        if self.layer.animation(forKey: kAnimationKey) != nil {
            self.layer.removeAnimation(forKey: kAnimationKey)
        }
    }
}

尝试调用我的图像视图以在viewDidLoad方法中开始旋转时,没有任何反应。

1 个答案:

答案 0 :(得分:0)

错误解释:

您正以AnyObject

的身份传递代理人
func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil)

AnyObject不符合CAAnimationDelegate,因此您无法将其用作代表。

如果您确定要传递的控制器可以是合适的代理人,那么请将其投放到合适的代表处:

if let delegate = completionDelegate as? CAAnimationDelegate {
    rotateAnimation.delegate = delegate
}

如果您正在执行此操作并且崩溃:

rotateAnimation.delegate = completionDelegate as! CAAnimationDelegate

然后你没有传入符合CAAnimationDelegate

的控制器

根本不能传递委托并将其分配到扩展名之外可能更简单。