我只是想问一下如何使用变量作为选择器。 我的代码如下所示:
NSString *stunde = [lesson objectForKey:@"stunde"]; // value is t1s1, then t1s2 then t1s3 etc.
t1s1.text=subject;
这没有问题。但是,由于我必须遍历40个标签,所以这样做会非常棒:
NSString *stunde = [lesson objectForKey:@"stunde"];
**stunde**.text=subject;
如何通过使用我在for循环中从json字符串获得的值动态地与标签交谈。
结果应如下所示:
NSString *stunde = [lesson objectForKey:@"stunde"];
t1s1.text=@"English";
NSString *stunde = [lesson objectForKey:@"stunde"];
t1s2.text=@"German";
NSString *stunde = [lesson objectForKey:@"stunde"];
t1s3.text=@"Business Studies";
等.....
我希望你能帮助我,知道我的意思
提前致谢
更新:
我刚开始工作(硬编码):
labels[0] = t1s1;
labels[1] = t1s2;
labels[2] = t1s3;
for (NSDictionary *lessons in list)
{
int TotalLessons = [list count];
NSString *fach = [lessons objectForKey:@"fach"];
UILabel *stunde = [lessons objectForKey:@"stunde"];
//labels[counter]=stunde;
labels[counter].text=fach;
counter=counter+1;
if(counter>=TotalLessons){
break;
}
}
但由于会有40-50个标签,我想将label_names动态添加到数组中: 像这样:
UILabel *stunde = [lessons objectForKey:@"stunde"];
labels[counter]=stunde;
值“stunde”将被定义为UILabel,然后添加到数组中。但为什么应用程序崩溃了?怎么了? :(
感谢
答案 0 :(得分:1)
您应该首先初始化这样的字典:
NSDictionary *Labels = [[NSDictionary alloc] initWithObjectsAndKeys:
LabelObject1, @"LabelObjectName1",
LabelObject2, @"LabelObjectName2",
LabelObject3, @"LabelObjectName3",
...
LabelObjectN, @"LabelObjectNameN",
nil];
然后您可以通过以下方式访问每个标签:
NSString *stunde = [lesson objectForKey:@"stunde"];
((UILabel *)[Labels objectForKey:stunde]).text = @"Some text";