Swift协议编程--UI动画

需求:实现一个360°旋转动画,凡是UIView子类(如UILabel, UIImageview, UIButton)都可以直接全局调用该动画方法。

效果图:


GlobalRotationAnimationDemo.gif

关键代码:

RotationAnimatonHelper.swift
import UIKit

//MARK: -RotationAnimatonProtocal
protocol RotationAnimatonProtocal {}

//MARK : -add RotationAnimaton func
extension RotationAnimatonProtocal where Self: UIView {
    
    func startRotationAnimation() {
        // 1.create
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")

        // 2.setting
        rotationAnim.fromValue = 0
        rotationAnim.toValue = Double.pi * 2
        rotationAnim.repeatCount = MAXFLOAT
        rotationAnim.duration = 0.6
        
        // 3.add to layer
        layer.add(rotationAnim, forKey: rotationAnimationKey)
    }
    
    func stopRotationAnimation() {
        layer.removeAnimation(forKey: rotationAnimationKey)
    }
   
    //MARK: -key
    var rotationAnimationKey: String {
        return "RotationAnimationKey"
    }
}

extension UIView: RotationAnimatonProtocal{}
之后在需要用到动画的地方调用即可,例如:
import UIKit

class ViewController: UIViewController {
    //MARK:-Vars
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    //Mark: -Event
    @IBAction func startDidPressed(_ sender: Any) {
        label.startRotationAnimation()
        button.startRotationAnimation()
        imageView.startRotationAnimation()
    }

    @IBAction func stopDidPressed(_ sender: Any) {
        label.stopRotationAnimation()
        button.stopRotationAnimation()
        imageView.stopRotationAnimation()
    }
}

demo传送

你可能感兴趣的:(Swift协议编程--UI动画)