UIButton is disabled - Swift

Viewed 364

I'm new to swift programming and I'm trying to disable the save button until all other required buttons are selected, but when I try to do that with the button.isEnabled = false, it doesn't change even when all the buttons are selected. here is a sample code:

func disableButton () {
    if firstButton.isSelected && rightButton.isSelected  {
        saveButton.isEnabled = true
    } else {
        saveButton.isEnabled = false
    }
}

when I remove the last line the save button works but when I put it back it's disabled even when the two other buttons are selected.

1 Answers

Assuming you have used Storyboard you have to link the 2 buttons into @IBActions , and within those @IBAction methods manipulate the isSelected property. Refer the example below.

NOTE - Read the comments

class ViewController: UIViewController {

    // 2 buttons that we will set the isSelected property
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!

    // Button to disable/enable
    @IBOutlet weak var finalButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        finalButton.isEnabled = false // setting the button as disabled
    }

    /// This is the function triggered when you click on the "button1"
    @IBAction func didPressButton1(_ sender: UIButton) {
        // Here we will set the isSelected property of "sender" parameter, which is the button that calls this function. That is button 1
        sender.isSelected = sender.isSelected ? false : true
        //calling this function to make any updates to the UI if needed
        disableButton()
    }

    /// This is the function triggered when you click on the "button2"
    @IBAction func didPressButton2(_ sender: UIButton) {
        // Here we will set the isSelected property of "sender" parameter, which is the button that calls this function. That is button2
        sender.isSelected = sender.isSelected ? false : true
        //calling this function to make any updates to the UI if needed
        disableButton()
    }

    func disableButton () {
        if button1.isSelected && button2.isSelected  {
            finalButton.isEnabled = true
        } else {
            finalButton.isEnabled = false
        }
    }
}

What happens here is you will set the isSelected property of the button that calls the function in the function itself, and run the disableButton() function every time it is invoked for UI updates. The final result will be,

enter image description here

Related