Skip to content

Instantly share code, notes, and snippets.

@apatronl
Created June 20, 2020 17:06
Show Gist options
  • Save apatronl/33e4b9fe968a8958830aa117f7ea677c to your computer and use it in GitHub Desktop.
Save apatronl/33e4b9fe968a8958830aa117f7ea677c to your computer and use it in GitHub Desktop.
import UIKit
class HeartButton: UIButton {
private var isLiked = false
private let unlikedImage = UIImage(named: "heart_empty")
private let likedImage = UIImage(named: "heart_filled")
private let unlikedScale: CGFloat = 0.7
private let likedScale: CGFloat = 1.3
override public init(frame: CGRect) {
super.init(frame: frame)
setImage(unlikedImage, for: .normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func flipLikedState() {
isLiked = !isLiked
animate()
}
private func animate() {
UIView.animate(withDuration: 0.1, animations: {
let newImage = self.isLiked ? self.likedImage : self.unlikedImage
let newScale = self.isLiked ? self.likedScale : self.unlikedScale
self.transform = self.transform.scaledBy(x: newScale, y: newScale)
self.setImage(newImage, for: .normal)
}, completion: { _ in
UIView.animate(withDuration: 0.1, animations: {
self.transform = CGAffineTransform.identity
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment