SnapChatみたいにフォーカス中だけ大きくなるUIButtonができたのでシェアします。
.touchDown
で大きくして、.touchUpInside, .touchUpOutside, .touchCancel
で小さくします。
IBActionでタップイベントを定義せずに、
button.setOnClickListener {[weak self] in
self?.thinkUnique()
}
みたいな感じで使います。
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")
}
}
gistにあげてます。
https://gist.github.com/kboy-silvergym/62de6540ee61d879ca584e707719e171