jay*_*ixz 1 iphone xcode uitableview sections
我有这个数据,我需要把它放在我的内容,UITableView但我对如何正确实现它感到困惑.我无法正确分隔值以将Boys数据与Girls数据分开.
{
"QUERY": {
"COLUMNS": [
"NAME",
"GENDER"
],
"DATA": [
[
"Anne",
"Girl"
],
[
"Alex",
"Boy"
],
[
"Vince",
"Boy"
],
[
"Jack",
"Boy"
],
[
"Shiela",
"Girl"
],
[
"Stacy",
"Girl"
]
]
},
"TOTALROWCOUNT": 6
}
Run Code Online (Sandbox Code Playgroud)
我有这个代码:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [genderArray count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [genderArray objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [namesArray count];
}
Run Code Online (Sandbox Code Playgroud)
namesArray具有NAME返回的所有值,而genderArray具有GENDER的所有值.我很困惑.
当你感到困惑时,将你的数据分成几部分.你想要两个数组,每个部分一个.所以你想要一个男孩名字阵列和另一组女孩名字.
您可以通过迭代嵌入的DATA数组来获得此结果.
将您的数据转换为NSDictionary对象.您的数据看起来像JSON所以......
NSDictionary* myDict = [NSJSONSerialization JSONObjectWithData:myJsonData
options:0 error:&error];
Run Code Online (Sandbox Code Playgroud)
提取数据......
NSArray* dataArray = [myDict objectForKey:@"DATA"];
Run Code Online (Sandbox Code Playgroud)
重复...
NSMutableArray* boys = [[NSMutableArray alloc] init];
NSMutableArray* girls = [[NSMutableArray alloc] init];
for (id person in dataArray) {
if ([[person objectAtIndex:1] isEqualToString:@"Girl"])
[girls addObject:[person objectAtIndex:0]];
else [boys addObject:[person objectAtIndex:0]];
}
Run Code Online (Sandbox Code Playgroud)
现在您有两个数组,每个数组对应一个表部分.创建一个部分数组,并将这些数组放入其中:
NSArray* sections = [NSArray arrayWithObjects:boys,girls,nil];
Run Code Online (Sandbox Code Playgroud)
为节标题创建一个单独的数组:
NSArray* headers = [NSArray arrayWithObjects:@"Boys",@"Girls",nil];
Run Code Online (Sandbox Code Playgroud)
现在您的数据源方法如下所示:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sections count];
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
return [headers objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [[sections objectAtIndex:section] count];
}
Run Code Online (Sandbox Code Playgroud)
最后
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
...
cell.textLabel.text = (NSString*)[[self.sections objectAtIndex:indexPath.section]
objectAtIndex:indexPath.row];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6396 次 |
| 最近记录: |