检查数组中按钮的文本

时间:2018-02-14 21:05:40

标签: ios arrays swift

我有5个按钮,它们在一个数组中。当按钮的文本不等于cevapLabel.Text时,我想隐藏它们随机化。如何检查所有按钮文字?

像这样; while allButtonsText != cevapLabel.Text {}

这是我的代码:

@IBAction func eliminateChoiceClicked(_ sender: Any) {

    let num = Int(arc4random_uniform(5))
    let buttons:[UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]
    while  buttons != cevapLabel.text {

        buttons[num].isHidden = !buttons[num].isHidden
    }

}

在此代码中显示此错误:"二元运算符'!='不能应用于' [UIButton]'类型的操作数和'字符串?' "

---的 EDITED ---

我必须在我的项目中进行一些更改。

以下是代码:

@IBAction func eliminateChoiceClicked(_ sender: Any) {

    var buttons: [UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]

    for _ in 1...3 {

        let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
        let button = buttons.remove(at: randomNumber)
        button.isHidden = true
    }

    for button in buttons {
        button.isHidden = false
    }

}

我试过这样:

@IBAction func eliminateChoiceClicked(_ sender: Any) {

    var buttons: [UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]
    for x in buttons {
        if x.titleLabel?.text != cevapLabel.text {

            for _ in 1...3 {

                let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
                let button = buttons.remove(at: randomNumber)
                button.isHidden = true
            }
        }
        else {
            for button in buttons {
                button.isHidden = false
            }
        }
    }
}

我得到了这个错误:"线程1:致命错误:索引超出范围"

3 个答案:

答案 0 :(得分:1)

出现此问题是因为您正在将UIButtons数组与String进行比较。

您可以通过创建一个返回Bool并在您的while语句中调用它的函数来修复您的问题,如下所示:

a <- ggplot(df, aes(x=X, y=Y, size = size)) + geom_point(colour = "dodgerblue3") + theme_bw()
ggplotly(a)

答案 1 :(得分:0)

我不明白是否需要while循环,我会用

替换它
if buttons.map($0.title).filter($0 == cevapLabel.text).count == 0 {
  buttons[num].isHidden = !buttons[num].isHidden
}

答案 2 :(得分:0)

Swift 4

for button in buttons {
    if button.title(for: .normal) == cevapLevel.text {
    //your code
   }
}