声明一个Shake动画的协议
protocol Shakeable {
}
给协议拓展一个shake的方法
extension Shakeable where Self: UIView {
func shake() {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 5
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x - 4, y: center.y - 4))
animation.toValue = NSValue(cgPoint: CGPoint(x: center.x + 4, y: center.y + 4))
layer.add(animation, forKey: "position")
}
}
写一个自定一个button 遵循协议
class ActionButton: UIButton,Shakeable {
}
之后创建ActionButton 就拥有了shake事件 ,如果其他控件也需要用到这个shake 只需要遵循shakeable协议即可