Skip to content

Instantly share code, notes, and snippets.

@guillianbalisi
Created July 12, 2018 18:38
Show Gist options
  • Save guillianbalisi/e98da9d1e108cb7bd069fc038d24946a to your computer and use it in GitHub Desktop.
Save guillianbalisi/e98da9d1e108cb7bd069fc038d24946a to your computer and use it in GitHub Desktop.
Change the image of UIButton with a bounce animation (reversible, for example liking/unliking with a heart image)
extension UIButton {
func setImage(_ image: UIImage?, animated: Bool = false, reversed: Bool = false, color: UIColor) {
guard animated else {
setImage(image, for: .normal)
return
}
let templateImage = image?.withRenderingMode(.alwaysTemplate)
tintColor = color
var values: [CATransform3D] = []
var keyTimes: [Float] = []
// Start scale
if !reversed {
values.append(CATransform3DMakeScale(0.0, 0.0, 0.0))
} else {
values.append(CATransform3DMakeScale(1.0, 1.0, 1.0))
}
keyTimes.append(0.0)
// Bounce scale
if !reversed {
values.append(CATransform3DMakeScale(1.35, 1.35, 1.35))
} else {
values.append(CATransform3DMakeScale(0.65, 0.65, 0.65))
}
keyTimes.append(0.5)
// End scale
if !reversed {
values.append(CATransform3DMakeScale(1.0, 1.0, 1.0))
} else {
values.append(CATransform3DMakeScale(0.0001, 0.0001, 0.0001))
}
keyTimes.append(1.0)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.values = values.map({ NSValue(caTransform3D: $0) })
animation.keyTimes = keyTimes.map({ NSNumber(value: $0 as Float) })
animation.isRemovedOnCompletion = true
animation.fillMode = kCAFillModeForwards
animation.duration = 0.3
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
imageView?.layer.add(animation, forKey: "animateContents")
setImage(templateImage, for: .normal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment