Joe Joe - 2 years ago 103
Swift Question

Restrict UIButton after number of clicks in Swift

I have a simple function running inside the UIButton.I want to restrict the user press the UIButton not more than 5 Times.I am not sure whether I have to use tap gesture to count the number clicks or button action method.please, Someone point me the direction.

Thanks in Advance

Answer Source

I suggest you to create your own button.

class MyButton: UIButton {

    private (set) var amountOfTouches: Int = 0 {
        didSet {
            if self.amountOfTouches >= 5 {
                self.enabled = false
                self.userInteractionEnabled = false

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        self.amountOfTouches += 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download