2015-10-20 38 views
0

我有多个按钮,都可以从数组中获得标题。我希望能够通过循环来分配标题,但是当我通过循环时,我无法确定如何引用每个按钮。Swift - 为多个按钮指定标题

目前,我将每个标题有这样的一行代码:

button0.setTitle(title[0], forState: .Normal) 
button1.setTitle(title[1], forState: .Normal) 
button2.setTitle(title[2], forState: .Normal) 
button3.setTitle(title[3], forState: .Normal) 
etc... 

我已经添加了一个IBOutlet到每个按钮,但我也使用标签用于其他目的,所以,如果有一种方法要使用标签分配标题,我很乐意这样做。

有什么想法?

+0

您可以使用标签此得到一个UIButton方式: 'UIButton * button =(UIButton *)[self.view viewWithTag:7];' – Randy

回答

1

你需要一个IBOutletCollection

在你斯威夫特视图控制器,将所有的按钮下面

@IBOutlet var buttons: [UIButton]! 

然后分配标题

var buttonTitles = ["Button1","Button2"] 

for (index,button) in buttons.enumerate() 
{ 
    if buttonTitles.count > index 
    { 
    if let title : String = buttonTitles[index] 
    { 
     button.setTitle(title, forState: .Normal) 
    } 
    } 
} 
+0

谢谢。正是我在找的东西。 – Eric