UIView+Rotating.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // UIView+A.swift
  3. // Pods
  4. //
  5. // Created by 100Years on 2025/3/6.
  6. //
  7. import UIKit
  8. public extension UIView {
  9. // MARK: - 旋转动画控制
  10. /// 开始旋转动画
  11. /// - Parameters:
  12. /// - duration: 单圈旋转时间(默认 1 秒)
  13. /// - clockwise: 是否顺时针旋转(默认 true)
  14. /// - repeatCount: 重复次数(默认无限循环 .greatestFiniteMagnitude)
  15. func startRotating(duration: CFTimeInterval = 1.0,
  16. clockwise: Bool = true,
  17. repeatCount: Float = .greatestFiniteMagnitude) {
  18. // 同步移除已有旋转动画
  19. self.stopRotating()
  20. DispatchQueue.main.async {
  21. // 创建旋转动画
  22. let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
  23. rotationAnimation.fromValue = 0
  24. rotationAnimation.toValue = clockwise ? CGFloat.pi * 2.0 : -CGFloat.pi * 2.0
  25. rotationAnimation.duration = duration
  26. rotationAnimation.isCumulative = true
  27. rotationAnimation.repeatCount = repeatCount
  28. rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
  29. // 防止动画结束后恢复初始状态
  30. rotationAnimation.fillMode = .forwards
  31. rotationAnimation.isRemovedOnCompletion = false
  32. // 添加动画到视图的 layer
  33. self.layer.add(rotationAnimation, forKey: "rotationAnimation")
  34. }
  35. }
  36. /// 停止旋转动画
  37. func stopRotating() {
  38. // 同步移除旋转动画
  39. DispatchQueue.main.async {
  40. self.layer.removeAnimation(forKey: "rotationAnimation")
  41. }
  42. }
  43. }