2013-10-28 67 views
-2

我在視圖控制器中有六個標籤,我在for循環中獲得六個字符串,如下所示。iOS:將消息傳遞給for循環中的不同標籤

for(NSDictionary *dictionary in array) 
{ 
    NSString *name = dictionary[@"Name"]; 
    NSLog(@"Name = %@ \n", name); 
} 

每當我在日誌中的名字,我想在不同的標籤(其中六)視圖控制器發送名稱。

如何將名稱對象/消息傳遞給標籤?你得到的每一次迭代不同的名稱/結果和迭代值傳遞給一個標籤

在for循環中獲得第1名,張貼標籤1.

在for循環中獲得第2名,張貼標籤2 和等..

+2

我能」理解正確的重量你說。請簡單介紹一下嗎? – TamilKing

+0

如何將名稱對象/消息傳遞給標籤?您爲每次迭代獲得不同的名稱/結果,並將這些迭代值傳遞給標籤。 –

回答

2
NSArray *lbls = [[NSArray alloc] initWithObjects:lbl1, lbl2, lbl3, lbl4, lbl5, lbl6, nil]; 

int i=0; 
for(NSDictionary *dictionary in array) 
{ 
    UILabel *lbl = (UILabel *)[lbls objectAtIndex:i++]; 
    [lbl setText:dictionary[@"Name"]; 
} 
0

您可以創建一個地圖的名稱,以相應的UILabel元素:

YourClass.h:

@interface YourClass : UIViewController { 
    NSMutableDictionary *_labelMap; 
    IBOutlet UILabel *_label1; // Connected in IB 
    IBOutlet UILabel *_label2; // Connected in IB 
    IBOutlet UILabel *_label3; // Connected in IB 
    IBOutlet UILabel *_label4; // Connected in IB 
    IBOutlet UILabel *_label5; // Connected in IB 
    IBOutlet UILabel *_label6; // Connected in IB 
} 

...

YourClass.m:

@implementation YourClass { 

- (void)viewDidLoad { 
    // Not done in init, as you need the labels to be connected once the NIB is loaded 
    _labelMap = [[NSMutableDictionary alloc] init]; 
    _labelMap[@"Name1"] = _label1; 
    _labelMap[@"Name2"] = _label2; 
    _labelMap[@"Name3"] = _label3; 
    _labelMap[@"Name4"] = _label4; 
    _labelMap[@"Name5"] = _label5; 
    _labelMap[@"Name6"] = _label6; 
    ... 
} 

- (void)yourMethod { 
    for(NSDictionary *dictionary in array) 
    { 
     NSString *name = dictionary[@"Name"]; 
     NSLog(@"Name = %@", name); // Don't need to add newline! 
     UILabel *field = _labelMap[name]; 
     field.text = name; 
    } 
}