-2

我在视图控制器中有六个标签,我在 for 循环中得到六个字符串,如下所示。

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

每当我在日志中获得一个名称时,我想将该名称以不同的标签(其中六个)发送到视图控制器。

如何将名称对象/消息传递给标签?您为每次迭代获得不同的名称/结果,并将这些迭代值传递给标签

在 for 循环中获取第一个名称,发布到标签 1。

在 for 循环中获取第二个名称,发布到标签 2 等等..

4

2 回答 2

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"];
}
于 2013-10-28T12:32:37.033 回答
0

您可以创建名称到相应UILabel元素的映射:

你的类.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
}

...

你的班级.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;
    }
}
于 2013-10-28T12:29:54.617 回答