2010-08-03 61 views
0

比方說,我有已成立了IB和連接到代碼IBOulets(LABEL1,LABEL2,LABEL3,label4)幾個UILabels如何在代碼中構建IBOutlet名稱以便更改它們?

如何我會創造中的代碼,這些變量名,這樣我就可以更改每個循環的文本,其中標籤是從NSArray中獲取的。

這裏是僞代碼:

labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", @"a", @"random", @"amount", @"of", @"items", nil]; 
for (int i = 0; i < [labelArray count]; i++) 
{ 
    // labelx is the constructed name of the IBOutlet 
    lablex.text = [labelArray objectAtIndex:i]; 

} 

如何構建上述 'labelx'?這可以使用塊來完成嗎?

+0

的lableArray具有動態的大小嗎?你想映射數組中的每個元素到UILabel?但是你沒有動態數量的標籤? 如果你真的想要這個,你最終可以使用 - (id)valueForKey:(NSString *)key(http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/Reference/ Reference.html) – V1ru8 2010-08-03 13:07:17

回答

2

你將不得不陣列在一些地方初始化,使用

labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", nil]; 
uiLabelArray = [NSArray arrayWithObjects:label1,label2,label3,nil]; 

然後

for (int i = 0; i < [uiLabelArray count]; i++) 
{ 
    [uiLabelArray objectAtIndex:i].text = [labelArray objectAtIndex:i]; 
} 
+0

我已經有了一個labelArray。問題是將該數組轉換成循環內的UILabels中的文本。 – cannyboy 2010-08-03 12:50:48

+0

然後製作2個數組。看到我更新的答案。 – mvds 2010-08-03 13:18:21

2

您可以使用鍵值編碼(KVC)。它看起來是這樣的:

[[self valueForKey:[NSString stringWithFormat:@"label%d", i]] setText:[labelArray objectAtIndex:i]];

更多信息,可以發現here

+0

Ewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww。 – 2010-08-03 18:12:23

相關問題