1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public enum ShakeDirection { case horizontal case vertical }
extension UIView { public func shake(direction: ShakeDirection = .horizontal, times: Int = 6, interval: TimeInterval = 0.1, delta: CGFloat = 4, completion: ((Bool) -> ())? = nil) { UIView.animate(withDuration: interval, animations: { switch direction { case .horizontal: self.layer.setAffineTransform( CGAffineTransform(translationX: delta, y: 0)) case .vertical: self.layer.setAffineTransform( CGAffineTransform(translationX: 0, y: delta)) }
}) { (_) in if (times == 0) { UIView.animate(withDuration: interval, animations: { self.layer.setAffineTransform(CGAffineTransform.identity) }, completion: completion) } else { self.shake(direction: direction, times: times - 1, interval: interval, delta: delta * -1, completion:completion) } } } }
|