gpt4 book ai didi

ios - 在 Swift 中制作旋转图像的动画

转载 作者:行者123 更新时间:2023-11-30 12:38:05 31 4
gpt4 key购买 nike

我有一个图像,如果按下按钮,我希望它继续旋转,直到我调用一个操作来停止旋转。我尝试了这些网站: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)
}
}

尝试将 delegate 转换为!尝试旋转图像时,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)
}
}
}

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

最佳答案

错误解释:

您将委托(delegate)作为 AnyObject 传递

func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil)

AnyObject 不符合 CAAnimationDelegate,因此您不能将其用作委托(delegate)。

如果您确定传入的 Controller 可以是适当的委托(delegate),则将其转换为正确类型的委托(delegate):

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

如果你这样做并且它崩溃了:

rotateAnimation.delegate = completionDelegate as! CAAnimationDelegate

那么您没有传入符合CAAnimationDelegate的 Controller

根本不传递委托(delegate)并将其分配到扩展程序之外可能会更简单。

关于ios - 在 Swift 中制作旋转图像的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42615070/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com