在Swift中动画旋转图像

问题描述:

如果按下按钮,我想要继续旋转图像,直到我调用停止旋转的动作。我试过这些网站:https://www.andrewcbancroft.com/2014/10/15/rotate-animation-in-swift/我不得不为代表团创造机会,当我尝试改变它时,它崩溃了 和https://bencoding.com/2015/07/27/spinning-uiimageview-using-swift/在我称之为动作时不会旋转。谢谢。代码是在这里如下:在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将使应用程序崩溃并显示错误代码尝试旋转图像时,无法将类型'test.ViewController'(0x1074a0a60)的值转换为'CAAnimationDelegate'(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方法旋转,没有任何反应。

+0

没有人会阅读这些网站上的代码并为您编写代码。发布您尝试过的代码和错误消息。 – Frankie

+0

好的,我更新了它 – Petravd1994

错误解释:

你传递作为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

控制器这可能是简单不能通过委托在所有并将其分配出局扩展名。