简体   繁体   中英

Rotate a view 360 degrees infinitely

I am using this code to rotate a view 360 degrees infinitely. But my view is not rotating:

func rotateImageView() {

        UIView.animate(withDuration: 3.0, delay: 0, options: [.repeat, .curveLinear], animations: {
            self.vinylView.transform = CGAffineTransform(rotationAngle: .pi * 2)
        })
        
    }

How to fix it?

Substitute pi * with /, delete repeat, add completion and recall the function like this:

private func rotateImageView() {
    UIView.animate(withDuration: 3, delay: 0, options: .curveLinear, animations: {
        self.vinylView.transform = self.vinylView.transform.rotated(by: .pi / 2)
    }) { (finished) in
        if finished {
            self.rotateImageView()
        }
    }
}

Solution using CABasicAnimation

// Rotate vinvlView
vinylView.layer.add(CABasicAnimation.rotation, forKey: nil)

extension CABasicAnimation {
    static let rotation : CABasicAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        animation.repeatCount = .infinity // Rotate a view 360 degrees infinitely
        animation.fromValue = 0
        animation.toValue = CGFloat.pi * 2
        animation.duration = 3.0
        return animation
    }()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM