【问题标题】:I need to infinitely rotate a view until told to stop我需要无限旋转视图直到被告知停止
【发布时间】:2017-04-25 11:14:19
【问题描述】:

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

这是我目前的代码。

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 中,Apple 让他们的飞机如此轻松地旋转,这应该不难。我试图避免删除并重新安装旧版本,以便查看该代码。

【问题讨论】:

    标签: ios swift animation uiview rotation


    【解决方案1】:

    其实会更简单:

       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()

    停止: 你的观点。停止旋转()

    【讨论】:

    • 我不熟悉“层”部分。我基本上将您的代码复制并粘贴到我的程序中,并试图使其全部正常工作,但我收到错误“ViewController 没有成员'层'”。因此,我在尝试调用它时也会出错。当我写 'myView'.rotate360Degrees() 它有一个错误说“UIImageView has no member 'rotate360Degrees'”。
    • 它是一个扩展,你需要做的就是将所有代码粘贴到你的课堂之外。然后你像 imageView.rotate() .. 一样使用它
    • 所以我在课堂外复制并粘贴了您的代码。 (在我的进口和我的班级之间)它说“使用未解析的标识符'self'”。对不起,如果这些是明显的问题,我还是习惯了。不过感谢您的帮助。
    • 没有问题的朋友,做一件事,创建任何名为 Extensions.swift 的空 swift 文件。将所有代码粘贴在那里,但记住一件事 import UIKit
    • 好的,所以我这样做了,但我仍然遇到与“self”相同的错误。我什至尝试删除 import Foundation,但同样的错误。
    【解决方案2】:

    您是否尝试在后半回合的完成块中再次调用 startRotating ?

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

    【讨论】:

    • 是的,我试过了,实际上我最终找到了一种方法来不断让它循环我正在走的路,但它变得越来越快,直到应用程序最终冻结。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多