Roberto Viramontes Roberto Viramontes - 3 months ago 10
Objective-C Question

How disable rest of the buttons from an array of buttons when button is pressed

Im having some trouble with method .disable in swift code. I have an array of Buttons and I want to disable the rest of Buttons when the correct Button (Target Button) is pressed. My array is call Buttons! Here are the action for the Buttons.
I have to have different names in the Buttons? or I can use .count method?
Thank you and appreciate everything.

@IBAction func btn1(sender: AnyObject) {
if answerNumber == 0 {
cwLabel.text = "You are Right!"
pickQuestion()
Buttons.count

} else {
cwLabel.text = "You are Wrong!"
pickQuestion()
}
}

@IBAction func btn2(sender: AnyObject) {
if answerNumber == 1 {
cwLabel.text = "You are Right!"
pickQuestion()

} else {
cwLabel.text = "You are Wrong!"
pickQuestion()
}
}

@IBAction func btn3(sender: AnyObject) {
if answerNumber == 2 {
cwLabel.text = "You are Right!"
pickQuestion()

} else {
cwLabel.text = "You are Wrong!"
pickQuestion()
}
}

@IBAction func btn4(sender: AnyObject) {
if answerNumber == 3 {
cwLabel.text = "You are Right!"
pickQuestion()

} else {
cwLabel.text = "You are Wrong!"
pickQuestion()
}
}

Answer

Use below line of code. It may help you...

for (var index = 0; index < arrayButton.count; index += 1) {
           let btn : UIButton = arrayButton[index] as UIButton
     btn.addTarget(self, action: #selector(self.toggleButtons toggleButtons(_:)), forControlEvents: .TouchUpInside)
        }

    func toggleButtons(button: UIButton) {
        for (var index = 0; index < arrayButton.count; index += 1) {
            if arrayButton[index] != button {
                arrayButton[index].enabled = false
            }
        }
    }