在swift 3中为uibuttons标题嵌套for循环

时间:2016-12-16 22:46:23

标签: for-loop swift3 nested-loops iboutletcollection

我有一个UIButtons的出口集合:

@IBOutlet var categoriesButtonLabels: [UIButton]!

每个按钮都有不同的标签(在故事板中设置)。

我想更改他们的标题填充一个字符串数组(我从我的FireBase数据库中检索代码中的其他地方的类别)。

我试过这样的事情:

override func viewDidLoad() {
    super.viewDidLoad()
// Setting Category buttons labels
    for button in categoriesButtonLabels {
        for i in categories {
            button.setTitle("\(i)", for: .normal)
        }
    }
}

但是它只获得categories数组的最后一个值,并为所有按钮设置标题相同... 我究竟做错了什么?

为了完整起见: 这是我的类别数组:

for (index, value) in categories.enumerated() {
print("\(index) = \(value)")
}

和outlet collection:

for (index, value) in categoriesButtonLabels.enumerated() {
print("\(index) = \(value)")
}

输出:

  

类别字符串数组是:0 =体育类别字符串数组是:1 =   科学类别字符串数组是:2 =电影类别字符串数组   是:3 =音乐类别字符串数组是:4 =历史

     

Outlet UIButtons Collection是:0 => Outlet UIButtons Collection是:1 =   > Outlet UIButtons Collection是:2 => Outlet UIButtons   收集是:3 =>出口   UIButtons Collection是:4 =>

1 个答案:

答案 0 :(得分:1)

删除内循环:

for (i, button) in categoriesButtonLabels.enumerated() {
    button.setTitle("\(categories[i])", for: .normal)
}
相关问题