我正在开发一个iOS应用程序,它将列出我存储在NSDictionary中的一些数据。我将使用表视图来执行此操作,但遇到了一些如何启动的问题。
数据看起来像这样:
category = (
{
description = (
{
id = 1;
name = Apple;
},
{
id = 5;
name = Pear;
},
{
id = 12;
name = Orange;
}
);
id = 2;
name = Fruits;
},
{
description = (
{
id = 4;
name = Milk;
},
{
id = 7;
name = Tea;
}
);
id = 5;
name = Drinks;
}
);
我试图将所有“类别”值作为表中的一个部分,并将每个“描述”中的“名称”放在正确的部分中。正如我提到的,不确定如何开始,我如何为每个“类别”获得一个新的部分?
发布于 2013-04-13 13:20:19
您“只需”实现表视图数据源方法来从字典中提取信息:-)
如果self.dict
是上面的字典,那么self.dict[@"category"]
是一个数组,每个部分包含一个字典。因此(使用“现代Objective-C下标语法”):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.dict[@"category"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return self.dict[@"category"][section][@"name"];
}
对于每个部分,
self.dict[@"category"][section][@"description"]
是每行包含一个字典的数组。因此:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dict[@"category"][section][@"description"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *name = self.dict[@"category"][indexPath.section][@"description"][indexPath.row][@"name"];
cell.textLabel.text = name;
return cell;
}
https://stackoverflow.com/questions/15987820
复制相似问题