Swift连续旋转动画不是那么连续

时间:2015-03-10 12:58:03

标签: ios xcode swift animation

这是我的代码。意图是连续旋转名为swirls [l]的UIImageView。但是,每个旋转开始/结束之间会有一个小的暂停。我已经完成了每一个动画教程,但无法弄清楚错误是什么?

let fullRotation = CGFloat(M_PI * 2)

    let duration = 2.0
    let delay = 0.0
    let options = UIViewKeyframeAnimationOptions.Repeat | UIViewKeyframeAnimationOptions.CalculationModeLinear

    UIView.animateKeyframesWithDuration(duration, delay: delay, options: options, animations: {
        UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1/3, animations: {
            swirls[l].transform = CGAffineTransformMakeRotation(1/3 * fullRotation)
        })
        UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
            swirls[l].transform = CGAffineTransformMakeRotation(2/3 * fullRotation)
        })
        UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
            swirls[l].transform = CGAffineTransformMakeRotation(3/3 * fullRotation)
        })

        }, completion: {finished in 
    })

编辑:我看到有人建议先前的解决方案可用,但它不能用于连续不间断的旋转。对我有用的唯一技巧是我在下面选择的答案。感谢

3 个答案:

答案 0 :(得分:36)

尝试以下扩展名为swift 4。

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

开始轮换。

MyView.rotate360Degrees()

对于停止。

MyView.layer.removeAllAnimations()

您可以使用UIButtonUILabel等等。

答案 1 :(得分:14)

我不确定你的代码有什么问题,但我已经使用这种方法实现了连续旋转,

@IBAction func rotateView(sender: UIButton) {

        UIView.animateWithDuration(0.5, delay: 0, options: .CurveLinear, animations: { () -> Void in
            self.spinningView.transform = CGAffineTransformRotate(self.spinningView.transform, CGFloat(M_PI_2))
        }) { (finished) -> Void in
            self.rotateView(sender)
        }
    }

答案 2 :(得分:6)

如果您想连续旋转按钮或查看并随时停止旋转,那么您可以尝试这样做: 对于开始轮换:

@IBOutlet weak var RotateBtn: UIButton!
var timeTimer: Timer?

viewDidLoad()
{
  self.rotateView()
  timeTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.rotateView), userInfo: nil, repeats: true)
}

func rotateView()
{
    UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: { () -> Void in
        self.RotateBtn.transform = self.RotateBtn.transform.rotated(by: CGFloat(M_PI_4))
    })
}

如果您想停止旋转,请使用:

@IBAction func StopBtn_Pressed(_ sender: AnyObject)
{
   timeTimer?.invalidate()
   self.RecordBtn.layer.removeAllAnimations()
}