0
@IBOutlet var buttons: [UIButton]!
@IBOutlet var labels: [UILabel]!

@IBAction func cevapSeçildi(_ sender: UIButton) {
    if sender == buttons[0] {
        `enter code here`
        labels[0].backgroundColor = UIColor.yellow 
    }
}

我要这个 ..

var x : Int

if sender == buttons[x] { labels[x].backgroundColor = UIColor.yellow }

你能帮我吗

4

2 回答 2

0

你可以得到按钮的索引

var index = buttons.index(of: sender)

然后设置

labels[index].backgroundColor = UIColor.yellow

如果您想同时将所有其他按钮设置为不同的颜色,请考虑:

let buttonIndex = buttons.index(of: sender)
for var label in labels {
    if(labels.index(of: label) == buttonIndex) {
        label.backgroundColor = UIColor.yellow
    } else {
        label.backgroundColor = UIColor.white
    }
}
于 2018-03-25T01:00:52.060 回答
0

几点:

  1. 使用按钮数组映射到单元格索引仅适用于单节表视图或集合视图。如果你有一个分段的表视图或一个在行和列中的集合视图,那么这种方法将不起作用。

  2. 如果您想将所选单元格上的标签设为黄色,而将所有其他单元格设为白色,则更改所有单元格是没有意义的。表格视图/集合视图一次只显示几个单元格,当您滚动时,这些单元格会被回收并用于表格视图/集合视图中的不同索引。

如果您让我知道您使用的是表格视图还是集合视图,我可以向您展示一种更好的方法。

编辑:

由于您没有使用表格视图或集合视图,因此直接操作标签确实有意义:

@IBAction func cevapSeçildi(_ sender: UIButton) {
    let buttonIndex = buttons.index(of: sender)
    for (index, label) in labels.enumerated) {
    }
    if index == buttonIndex {
        label.backgroundColor = UIColor.yellow 
    } else {
        label.backgroundColor = UIColor.white
    } 
}
于 2018-03-25T12:51:37.297 回答