Home > OS >  How to disable a button when a function is running in swift?
How to disable a button when a function is running in swift?

Time:11-18

I'm writing my own program in Swift. Here's how I define my button:

@IBAction func Button(_ sender: NSButton) {
    //blablabla
}
...

To prevent users from spamming this button again and again, I want each time users click this button, it will be disabled until the function completes. I've searched for this on the Internet, and one solution is to use Button.isEnabled = false. However, my type of definition does not allow me to use Button.isEnabled = false. It returned this error:

Value of type 'AppDelegate' has no member 'isEnabled'

In conclusion, my question is: how to disable the button itself when a function is running? Huge thanks!

CodePudding user response:

It's throwing error because your function's name is Button. If you want to disable button, you have to use the variable which represents the button.

@IBAction func Button(_ sender: NSButton) {
    sender.isEnabled = false
    //blablabla
    sender.isEnabled = true
}

This will keep the button disabled while blablabla is being executed

CodePudding user response:

You can disable / enable user interaction and easily handle this issue as-

yourButton.isUserInteractionEnabled = false // disabled
yourButton.isUserInteractionEnabled = true // enabled
  • Related