2015-10-20 39 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