旋转的菊花
2022-06-16 本文已影响0人
大刘
Created by 大刘 liuxing8807@126.com
一次小记录: UI同学设计了一个旋转的菊花,不使用 UIActivityIndicatorView
,于是我们用代码实现,这是一个非常小的功能,不过,直接让view本身旋转并不太合适,旋转本身和视图可以分离
import Foundation
import UIKit
class ZZRotation: NSObject {
var isAnimating: Bool = false
weak var attachView: UIView? = nil
/// Start attachView rotation
func start() {
guard let _ = self.attachView else {
return
}
if !self.isAnimating {
self.isAnimating = true
start(option: UIView.AnimationOptions.curveEaseIn)
}
}
func start(option: UIView.AnimationOptions) {
// this spin completes 360 degrees every 2 seconds
UIView.animate(withDuration: 0.3, delay: 0.0, options: option) {
print("en")
guard let attachView = self.attachView else {
return
}
attachView.transform = attachView.transform.rotated(by: CGFloat.pi/2)
} completion: { (isFinish) in
if isFinish {
if self.isAnimating {
// if flag still set, keep spinning with constant speed
self.start(option: UIView.AnimationOptions.curveLinear)
} else {
// one last spin, with deceleration
self.start(option: UIView.AnimationOptions.curveEaseOut)
}
}
}
}
/// Stop attachView rotation
func stop() {
guard let _ = self.attachView else {
return
}
}
}
测试
import UIKit
class ViewController: UIViewController {
let imageView: UIImageView = UIImageView()
let rotation: ZZRotation = ZZRotation()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
let image: UIImage = UIImage(named: "spin")!
imageView.frame = CGRect.init(x: 0, y: 0, width: image.size.width+10, height: image.size.height+10)
imageView.center = self.view.center
imageView.image = image
self.view.addSubview(imageView)
self.rotation.attachView = imageView
self.rotation.start()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.rotation.stop()
}
}