您的位置:首页 > 移动开发 > Objective-C

7.汽车品牌(表格分组数据)

2015-06-10 15:38 609 查看
实现目的:使用代码实现表格的分组数据。按照字母表的顺序,将每个汽车的品牌排列,并且将其分组,每个cell中左侧显示其标志,右侧显示名称。在最后侧添加字母顺序,点击字符跳转到该字母开头位置。

分析:在这个小项目中使用的.plist文件有多层,即Root目录下是一个Dictionary,里面又包含有cars的Array和一个title的字符串,其中在cars中多个字典。首先要将cars转换成模型,然后将最外层的字典转换成模型。之后,将ViewController设置数据代理,实现数据源方。最后添加右侧索引。

效果演示:



代码实现:ViewController.m 中代码:

- (UITableView *)tableView
{

if (_tableView == nil) {
CGFloat h = self.view.bounds.origin.y +20;
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, h, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
}
_tableView.dataSource = self;

[self.view addSubview:_tableView];

return _tableView;
}

// 懒加载
- (NSArray *)carGroups
{
if (_carGroups == nil) {
_carGroups = [CarGroup carGroups];
}
return _carGroups;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self tableView];

}
// 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.carGroups.count;
}
// 每组的总数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
CarGroup *group = self.carGroups[section];

return group.cars.count;
}

// 单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 查找可重用的单元格
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//如果没有可以重用的cell 实例化
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
// 设置cell的内容
CarGroup *group = self.carGroups [indexPath.section];
Car *car = group.cars [indexPath.row];

// 设置数据
cell.imageView.image = [UIImage imageNamed:car.icon];
cell.textLabel.text = car.name;

return cell;
}
// 标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
CarGroup *group = self.carGroups[section];

return group.title;
}
// 右侧索引列表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [self.carGroups valueForKeyPath:@"title"];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UI plist objective-c