6

I have button that show up a modal view but i want that if the user click it he wont be able to use it again for 90 seconds. how can i do this?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Ludyem
  • 1,709
  • 1
  • 18
  • 33

4 Answers4

15

In the IBAction of the button disable the button and set a timer like this:

self.button.enabled = false
NSTimer.scheduledTimerWithTimeInterval(90, target: self, selector: "enableButton", userInfo: nil, repeats: false)

And create the func called when the timer ends counting:

func enableButton() {
    self.button.enabled = true
} 
diegomen
  • 1,804
  • 1
  • 23
  • 37
8

Swift 4

sender.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 90, repeats: false, block: { _ in
    sender.isUserInteractionEnabled = true
})
Community
  • 1
  • 1
Vladimir
  • 1,053
  • 10
  • 8
3

#Swift 3

Write this code where you want to disable button.

self.buttonTest.isEnabled = false
Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(ViewController.enableButton), userInfo: nil, repeats: false)

Here buttonTest is the Outlet of that button.

And Write this code anywhere inside of your ViewController

 func enableButton() {
        self.buttonTest.isEnabled = true
    }

Let me know for any clarification. Thank You.

imagngames
  • 350
  • 7
  • 19
0

Swift 3

I wanted this answer to be much generic so developers find it more helpful

first , is the button hooked as an Outlet or as an action ? in both cases you will need to connect it as an outlet

second, I recommend you using a closure instead of writing a func then calling it you can simply do the following

   @IBOutlet weak var buttonWithTimer: UIButton!{
    didSet{
        self.buttonWithTimer.isEnabled = false
        Timer.scheduledTimer(withTimeInterval: 90, repeats: false) {  
             [weak self]timer in
            self?.buttonWithTimer.isEnabled = true
        } // [weak self]inside the closure is to break a possible    
          // memory sicle  
    }
}
Community
  • 1
  • 1
Harvester Haidar
  • 531
  • 7
  • 16