如何在点击按钮后禁用几秒钟

Jam*_*hen 2 button ibaction ios swift

下面是一个 IBAction 的代码,我想在点击它后禁用 5 秒。

@IBAction func postPressed(sender: AnyObject) {
        //var disableMyButton = sender as? UIButton
        //disableMyButton!.enabled = false
        //NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector:"enableButton", userInfo: nil, repeats: false)
    if(currLocation != nil){
        let testObject = PFObject(className: "Hey")
        testObject["text"] = self.postView.text
        testObject["count"] = 0
        testObject["replies"] = 0            
        testObject["location"] = PFGeoPoint(latitude: currLocation!.latitude , longitude: currLocation!.longitude)
        testObject["comments"] = []
        testObject["user"] = PFUser.currentUser()
        testObject.saveInBackgroundWithBlock({ (success, error) -> Void in
            if success {
                self.dismissViewControllerAnimated(true , completion: nil)
                if let completion = self.completion {
                    completion(self)
                }
            }
        })
    } else {
        alert()
    }  
}
Run Code Online (Sandbox Code Playgroud)

注释掉的代码是我尝试禁用按钮 5 秒钟,但是此代码崩溃了,我相信它崩溃了,因为没有对启用按钮的引用。

通常我会做类似的事情

func enableButton() {
   self.button.enabled = true
}
Run Code Online (Sandbox Code Playgroud)

但这不会起作用,因为它是一个 IBAction 并且除了那里没有对按钮的引用。也许有办法做到这一点,但我不知所措。

在此先感谢您的帮助。

小智 5

尝试这个,

  1. 同时点击操作设置按钮禁用。
  2. 通过使用延迟功能设置一些间隔以启用您的按钮。

前任:

let tapGesture = UITapGestureRecognizer(target: self, action: "tapaction")
tapGesture.numberOfTapsRequired = 1
Your_Button_name.addGestureRecognizer(tapGesture)


@IBAction func tapaction()
{
    Your_Button_name.disable=true
    //Delay function to enable your button
    NSTimer.scheduledTimerWithTimeInterval(Your_time_value_delay, target: self, selector: Selector("enablefunc"), userInfo: nil, repeats: false)
}

func enablefunc()
{
   Your_Button_name.disable=false
}
Run Code Online (Sandbox Code Playgroud)