How to shake NSView in macOS

Issue #233

Animation on macOS using CAAnimation

Shake

1
2
3
4
5
6
7
8
9
10
let midX = box.layer?.position.x ?? 0
let midY = box.layer?.position.y ?? 0

let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.06
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = CGPoint(x: midX - 10, y: midY)
animation.toValue = CGPoint(x: midX + 10, y: midY)
box.layer?.add(animation, forKey: "position")

Animation on macOS using NSAnimationContext

Wiggle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSAnimationContext.runAnimationGroup({ context in
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.beginTime = CACurrentMediaTime() + 5.0
animation.duration = 0.1
animation.autoreverses = true
let wobbleAngle: CGFloat = 0.08
animation.values = [
NSValue(caTransform3D: CATransform3DMakeRotation(wobbleAngle, 0.0, 0.0, 1.0)),
NSValue(caTransform3D: CATransform3DMakeRotation(-wobbleAngle, 0.0, 0.0, 1.0))
]
view.layer?.add(animation, forKey: "transform")
}, completionHandler: {
self.makeAnimation(view: view)
})

Animation on iOS using UIView animation block

1
2
3
4
5
6
7
8
extension UIView {
func shake() {
self.transform = CGAffineTransform(translationX: 16, y: 0)
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.transform = CGAffineTransform.identity
}, completion: nil)
}
}

Comments