将 UILabel 旋转 360 度或旋转动画

问题描述 投票:0回答:1

因为我是核心动画的初学者。我正在尝试重复旋转标签 360 度,或者你可以说是连续圆周运动。

func rotateLabel() {
        UIView.animate(withDuration: 1, delay: 0.2, options: .repeat) {
            let angle : CGFloat = .pi * 2.0
            self.locLabel.transform = CGAffineTransform(rotationAngle: angle)
        }

这是我将角度设置为等于 pi 或除以某个值时的函数

let angle : CGFloat = .pi
let angle : CGFloat = .pi/2
它开始旋转。但是当我将 pi 乘以某个值时,它不会执行任何动画。

ios swift xcode animation core-animation
1个回答
0
投票

希望这段代码对你有帮助

Import UIKit
    
    extension UIView {

            func startRotating(duration: CFTimeInterval = 3, repeatCount: Float = Float.infinity, clockwise: Bool = true) {
    
                if self.layer.animation(forKey: "transform.rotation.z") != nil {
                    return
                }
    
                let animation = CABasicAnimation(keyPath: "transform.rotation.z")
                let direction = clockwise ? 1.0 : -1.0
                animation.toValue = NSNumber(value: .pi * 2 * direction)
                animation.duration = duration
                animation.isCumulative = true
                animation.repeatCount = repeatCount
                self.layer.add(animation, forKey:"transform.rotation.z")
            }
    
            func stopRotating() {
    
                self.layer.removeAnimation(forKey: "transform.rotation.z")
    
            }   
    
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.