This UIButton changes own size like Snapchat buttons.
It will turn bigger during forcusing, and will turn default size when you release.
import UIKit
class MicroInteractButton: UIButton {
private var clickListener: (() -> Void)?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupAnimation()
adjustsImageWhenHighlighted = false
}
func setOnClickListener(_ completion: (() -> Void)?) {
clickListener = completion
}
private func setupAnimation(){
addTarget(self, action: #selector(pressed), for: [.touchDown])
addTarget(self, action: #selector(released), for: [.touchUpInside, .touchUpOutside, .touchCancel])
}
@objc private func pressed(){
expandAnimation()
}
@objc private func released(){
shrinkAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.clickListener?()
}
}
private func expandAnimation() {
let expand = CASpringAnimation(keyPath: "transform.scale")
expand.duration = 0.2
expand.fromValue = 1
expand.toValue = 1.3
expand.autoreverses = false
expand.repeatCount = 1
expand.initialVelocity = 0.8
expand.damping = 1.0
expand.fillMode = kCAFillModeForwards
expand.isRemovedOnCompletion = false
layer.bounds = self.bounds
layer.contentsGravity = "center"
layer.add(expand, forKey: "expand")
}
private func shrinkAnimation() {
let shrink = CABasicAnimation(keyPath: "transform.scale")
shrink.duration = 0.2
shrink.fromValue = 1.3
shrink.toValue = 1
shrink.autoreverses = false
shrink.repeatCount = 1
shrink.fillMode = kCAFillModeForwards
shrink.isRemovedOnCompletion = false
layer.add(shrink, forKey: "shrink")
}
}