简体   繁体   中英

Custom UIButton class with animation swift

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?

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 ...
    }
}

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)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM