Rotate a view for 360 degrees indefinitely in Swift?

后端 未结 10 1212
闹比i
闹比i 2020-12-05 13:06

I want to rotate an image view for 360 degrees indefinitely.

UIView.animate(withDuration: 2, delay: 0, options: [.repeat], animations: {
    self.view.transf         


        
10条回答
  •  时光说笑
    2020-12-05 13:55

    Avoiding the completion closure with recursive calls!

    Bit late to this party, but using UIView keyFrame animation & varying stages of rotation for each keyFrame, plus setting the animation curve works nicely. Here's an UIView class function -

    class func rotate360(_ view: UIView, duration: TimeInterval, repeating: Bool = true) {
    
        let transform1 = CGAffineTransform(rotationAngle: .pi * 0.75)
        let transform2 = CGAffineTransform(rotationAngle: .pi * 1.5)
    
        let animationOptions: UInt
        if repeating {
            animationOptions = UIView.AnimationOptions.curveLinear.rawValue | UIView.AnimationOptions.repeat.rawValue
        } else {
            animationOptions = UIView.AnimationOptions.curveLinear.rawValue
        }
    
        let keyFrameAnimationOptions = UIView.KeyframeAnimationOptions(rawValue: animationOptions)
    
        UIView.animateKeyframes(withDuration: duration, delay: 0, options: [keyFrameAnimationOptions, .calculationModeLinear], animations: {
            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.375) {
                view.transform = transform1
            }
            UIView.addKeyframe(withRelativeStartTime: 0.375, relativeDuration: 0.375) {
                view.transform = transform2
            }
            UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25) {
                view.transform = .identity
            }
        }, completion: nil)
    }
    

    Looks pretty gnarly, with the weird rotation angles, but as the op & others have found, you can't just tell it to rotate 360

提交回复
热议问题