如何使用动态JSON数据设置numberOfSectionsInTableView,titleForHeaderInSection [英] How to set numberOfSectionsInTableView, titleForHeaderInSection using dynamic json data
问题描述
我在下面提供了一些json数据,我想将其显示在表格标题中的表格中,这些表格的标题分别是Departments,Designing,Employees,Development,Employees.
I have some json data given below and I want to display it in a table where the section headers are Departments, Designing, Employees, Developing, Employees.
我在numberOfSectionsInTableView
,titleForHeaderInSection
中使用了静态数据,但我想使用动态数据来实现.
I used static data in numberOfSectionsInTableView
, titleForHeaderInSection
but I want to do it using dynamic data.
我该怎么做?
{
"Departments":[
{
"name":"Designing",
"id":"1.1",
"Employees":[
{
"name":"Ramesh",
"id":"1.1.1",
"salary":"4lakhs"
},
{
"name":"Suresh",
"id":"1.1.2",
"salary":"4lakhs"
}
]
},
{
"name":"Developing",
"id":"1.2",
"Employees":[
{
"name":"Ram",
"id":"1.2.1",
"salary":"4lakhs"
},
{
"name":"Sam",
"id":"1.2.2",
"salary":"4lakhs"
}
]
}
}
推荐答案
首先,您必须根据指定的字符串JSON对象创建一个NSDictionary.
first you have to create a NSDictionary from the string JSON object you specified.
NSDictionary *myDict = [NSJSONSerialization JSONObjectWithData:webData options:nil error:NULL];
然后在表视图中委派方法:
Then in the table view delegate methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[myDict valueForKey:@"Departments"] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[[myDict valueForKey:@"Departments"] objectAtIndex:section] valueForKey:@"Employees"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[myDict valueForKey:@"Departments"] objectAtIndex:section] valueForKey:@"name"];
}
或者至少我会尝试这样设置它们.
Or at least I would try to set them like this.
这篇关于如何使用动态JSON数据设置numberOfSectionsInTableView,titleForHeaderInSection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!