在swift中按下时,禁用按钮90秒



我有一个显示模式视图的按钮,但我希望如果用户单击它,他将无法在90秒内再次使用它。我该怎么做?

在按钮的IBAction中禁用按钮并设置计时器,如下所示:

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

并创建计时器结束计数时调用的函数:

func enableButton() {
    self.button.enabled = true
} 

Swift 4

sender.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 90, repeats: false, block: { _ in
    sender.isUserInteractionEnabled = true
})

#Swift 3

在您想要禁用按钮的地方写下这段代码。

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

这里的按钮Test是那个按钮的出口。

并在ViewController 内的任何位置编写此代码

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

如果有任何澄清,请告诉我。非常感谢。

Swift 3

我希望这个答案是通用的,这样开发人员就会发现它对更有帮助

首先,按钮是作为一个出口还是作为一个动作?在这两种情况下,您都需要将其连接为出口

其次,我建议您使用闭包,而不是编写函数,然后调用它,您可以简单地执行以下

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

最新更新