2.5,数据加载完以后,然后就要开始写UItable View中相对应的代理方法了
代码如下:
//设置分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.carGroups.count;
}
//设置每个分区显示多少行数据
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
ZKCarGroupModel *Model=self.carGroups[section];
return Model.cars.count;
}
//每行显示的数据
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID=@"A";
//从缓存中读取cell
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
//如果缓存中没有cell,创建一个新的cell
if(cell==nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//找到当前分区的索引
ZKCarGroupModel *GroupModel=self.carGroups[indexPath.section];
//找到当前分区的行
ZKCarModel *CarModel=GroupModel.cars[indexPath.row];
//设置cell显示的文字
cell.textLabel.text=CarModel.name;
//设置cell显示的图片
cell.imageView.image=[UIImage imageNamed:CarModel.icon];
return cell;
}
上面3个代理方法是UItable View中最常用的3个方法。写完这3个方法运行xcode就可以看到数据了。
但这里还有些小问题,这里显示的所有品牌都是从上往下排的,没有一个分组,这样我们想找哪个品牌的汽车并不太好找,所以,我们要把同一个数据的汽车品牌加一个字母表示,这怎么做呢,这就要给UItable View的每个分区加一个头了,使用titleForHeaderInSection代理方法
代码如下:
//设置头样式
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//找到当前分区在数组中的索引
ZKCarGroupModel *Model=self.carGroups[section];
//返回当前分区的数据中的title
return Model.title;
}
2.6上面的程序中,在屏幕的最右边还有一个索引,点这个索引就找找到相对应的分区数据,其实这个也很简单,也是调用一个
sectionIndexTitlesForTableView的代理方法,这个方法返回一个array的数组。
代码如下:
//设置索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [self.carGroups valueForKeyPath:@"title"];
}
2.7,这个程序中还做了一个,当你点击屏幕上每个汽车品牌的时候还会弹出一个对话框,为什么要做这个呢,因为很多时候屏幕上的图片和文字都是可以点击的,所以光做一个静态显示好不是很好,虽然这个对话框好像并没有什么用,但这里只是讲下这个方法的使用










