Reputation: 151
Is it possible to create a UIButton class with an onclick animation which gets automatically invoked everytime the user touches the button?
import UIKit
class AnimatedButton: UIButton {
@objc private func buttonClicked(sender: UIButton) {
sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
// animation ...
}
}
So I dont want to create an action in a ViewController in which button.buttonclicked() must be invoked. This should happen automatically everytime I use this class.
Is there any possibility to do something like that?
Upvotes: 2
Views: 2054
Reputation: 6611
Below code when you tap on button it will call animate method and perform animation. When you want to perform animation on button just assign AnimatedButton
class as Custom Class of UIButton :
class AnimatedButton: UIButton {
override func draw(_ rect: CGRect) {
self.addTarget(self, action: #selector(animate), for: .touchUpInside)
}
@objc func animate() {
self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
}
}
Upvotes: 2
Reputation:
You can do something like below, just replace the event which ever you are interested in.
class AnimatedButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(AnimatedButton.buttonClicked(sender:)), for: .touchUpInside)
}
@objc private func buttonClicked(sender: UIButton) {
sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
// animation ...
}
}
Upvotes: 3