如何在按下按钮时禁用按钮阵列中的其余按钮

时间:2016-08-31 03:14:26

标签: objective-c arrays swift uibutton

我在swift代码中使用.disable方法遇到了一些问题。我有一个按钮数组,我想在按下正确的按钮(目标按钮)时禁用其余的按钮。我的阵列叫按钮!以下是按钮的动作。 我必须在按钮中有不同的名字?或者我可以使用.count方法? 谢谢你,欣赏一切。

@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()
    }
}

2 个答案:

答案 0 :(得分:1)

使用以下代码行。它可能对你有帮助......

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
            }
        }
    }

答案 1 :(得分:0)

你的意思是禁用所有按钮或按下的按钮吗?您可以使用切换

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