How to prevent repeated button clicks in iOS?

I would like the button to be pressed some time after it has been successfully pressed.
My first thought is for the user to have a timer and turn off the button for a certain time, m unsure how to implement this.

Can someone point me in the right direction?

I use fast.

+4
source share
5 answers

No timer required. No shutdown required.

, . , . , , .

, , .

debouncing . , .

+7

, .

:

var ButtonIsActiv = false

func buttonPressed(button: UIButton) {
    if ButtonIsActiv == false {
       // do something with your button
       ButtonIsActiv = true

       // after 3 seconds, activate it again

       DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
           ButtonIsActiv = false
       }

    } else {
       // your button is not activated
    }
}
+3

?

//
//  ViewController.swift
//  SwiftButtonStopStackOverflow
//
//  Created by Seoksoon Jang on 29/09/2016.
//  Copyright © 2016 Seoksoon Jang. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet var testButton: UIButton!
    @IBAction func clickAction(_ sender: AnyObject) {

        self.testButton.isEnabled = !self.testButton.isEnabled

        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.testButton.isEnabled = !self.testButton.isEnabled
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
+1

Swift 3.0

, :

extension UIButton {
    func preventRepeatedPresses(inNext seconds: Double = 1) {
        self.isUserInteractionEnabled = false
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds) {
            self.isUserInteractionEnabled = true
        }
    }
}

:

@IBAction func pressedButton(_ sender: UIButton) {
     sender.preventRepeatedPresses()
     // do the job
}
+1

You can have a Bool in your controller that says the button is valid or not, and when the button is pressed, install Bool and schedule a TimeInterval, for example: Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(<YourMethod>), userInfo: nil, repeats: false)

Another strategy would be to press the button, turn off interaction with the property userInteractionEnabled, and then use the timer to turn the property back on.

0
source

Source: https://habr.com/ru/post/1656209/


All Articles