Search code examples
swiftuiviewibactionuser-interaction

Enable user interaction of a button SWIFT


OK, so lets assume the button created below is greyed out and user interaction disabled.

How do I enable the button from anywhere else.

I know how to disable the button from inside the button function, sender.enabled = false, but I don't want to disable it from there.

I want to re-enable the user interaction from outside the button function.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func loadButton(sender: UIButton) {
      //i wan to enable interaction of this button via override func and         NSUserDefaults
    }
}

Solution

  • In iOS and OS X development you have so-called outlets that are variables pointing to UI elements. You can read more about them here.

    To declare an outlet, you prefix your variable with @IBOutlet like so:

    @IBOutlet weak var button: UIButton!

    and then you need to connect your outlet to the button in your xib file. That can be done in several ways, but if you have declared a variable like the above, you can:

    1. go to your storyboard
    2. in the document outline hold down the control button
    3. while holding down the control button, you drag from your files owner or ViewController to the UIButton you'd like to connect to
    4. select the outlet you'd like to connect to (button in this case)

    As shown here

    One way to connect an outlet

    Once that is in place, you are free to use enable your button (and much more) in your code, for instance:

    func viewDidLoad() {
        super.viewDidLoad()
        button.enabled = false
    }
    

    You can read more about IBOutlets here

    And here is another way to connect outlets (this is how I prefer to connect outlets actually, you define and connect in one go)

    Hope that helps