我是 iOS 编程的新手,我有一个关于为标签赋值的问题,下面是我从服务中得到的结果
(
{
EmpName = Peter;
Relation = SouthAfrica;
},
{
EmpName = Smith;
Relation = WestIndies;
},
{
EmpName = Andrew;
Relation = England;
},
{
EmpName = John;
Relation = Australia;
},
{
EmpName = Rahul;
Relation = India;
}
)
上面我有 5 条记录,我的问题是如何将每个 EmpName 分配给 5 个标签,比如 peter 分配给 Label1,Smith 分配给 Label2,Andrew 分配给 Label3 等等。我只得到第一个 empName,下面是我试过的代码。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
jsonArray=nil;
NSLog(@"responseString is%@",responseString);
jsonArray=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments|NSJSONReadingMutableLeaves error:nil];
profileArray=[jsonArray mutableCopy];
NSLog(@"%lu",(unsigned long)[jsonArray count]);
if ([jsonArray count]==0) {
NSLog(@"responseString is%@",responseString);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Validation" message:@"Error Connecting to server" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
Label1.text = [[jsonArray objectAtIndex:0]objectForKey:@"EmpName"];
}
}
最佳答案
将标签添加到您的标签中(例如 tag = 1 用于 label1,tag = 2 用于 label2 ..... tag = 5 in label5)然后在您的 else 部分中您可以获得所有带有标签的标签。
for (int i = 0; i < jsonArray.count; i++) {
UILabel *lbl = (UILabel *)[self.view viewWithTag:i];
lbl.text = [[jsonArray objectAtIndex:i] objectForKey:@"EmpName"];
}
关于ios - 为标签 Objective-C 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42757370/