How do I disable individual UIButton (when pressed) under outlet collection?

132 views Asked by At

I'm new to swift,
Essentially what I want to do is after I press the UIbutton, I would like it to be disabled.

I know how to disable UIbutton when individual UIbutton is only linked to an outlet not an outlet collection.

with outlet:

I just list out individual buttons and disable them when pressed

@IBAction func NumButton1(_ sender: UIButton) 

{
        pressButton(outputnumber: "1", with: 1, on: sender)
        button1.isEnabled = false
}

@IBAction func NumButton3(_ sender: UIButton) 

{
        pressButton(outputnumber: "3", with: 3, on: sender)
        button2.isEnabled = false
}

...


@IBAction func NumButton9(_ sender: UIButton) 

{
        pressButton(outputnumber: "9", with: 9, on: sender)
        button3.isEnabled = false
}

with outlet collection:

@IBAction func NumButton(_ sender: UIButton) 

{
        let buttonNumber = buttons.index(of: sender)!

        let randomNumber = buttons.index(of: sender)!

        pressButton(outputnumber: numberDisplayed[buttonNumber], with: numberGuessed[randomNumber], on: sender)

If I linked a collection of UIbuttons to an outlet collection, how do I disable ANY of the UIbutton when ANY of them is pressed?

1

There are 1 answers

0
peekay On

If you just want to disable the clicked button, of course you can just use sender.isEnabled = false.

If you want to be able to disable any arbitrary button when any of them is clicked, then you can tag each button with a number so it can be identified, from the Attributes Inspector (towards the bottom):

enter image description here

So each button can be individually tagged with 0, 1, 2, 3, 4, etc. Then in your action you can refer to the tag number:

    @IBAction func myButtonPressed(_ sender: UIButton) {
        print("button pressed, with tag: \(sender.tag)")
    }

You can find any button by its tag using something like:

    func findButton(withTag: Int) -> UIButton? {
        return myButtonCollection.first { (btn) -> Bool in
            btn.tag == withTag
        }
    }