1.UITableView默认只是一个空壳子
2.TabeleView不知到内部需要显示什么样内容,如何才能告诉tableView中显示内容呢?
3.它需要一个专门为它提供数据的代理-数据源
设置数据源三个步骤:
1.遵守数据源协议
2.设置设置控制器为tableView数据源
3.实现数据源方法
三个核心方法:
//1.tableView中一共有多少组
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
//2.tableView 每一组多少行
// 在section对应这个组有多少行
// 注意:section从0开始
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//3.每一行展示什么样内容
// indexPath.section 第几组
// indexPath.row 第几行
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//4.设置组标题
// 用来告诉tableView第section组的头部应该显示什么样的内容
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//5.Footer 脚部,尾部,底部
//用来告诉tableView第section组的底部显示什么样内容
- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
tableView的代理
使用场景:当需要监听tableView中的cell的选中或取消选中的时候,可以设置tableView的代理
步骤:
1.遵守UITableDelegate协议
2.让控制器成为tableView的代理
3.实现需要监听代理方法
//当用户选中某一行的时候,会调用的代理方法
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//当用户取消选中某一个行的时候调用
- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
//该方法可以为不同行指定不同的行高
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
// 实现分组索引
- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView
{
// 存放标题
NSMutableArray *arrayM = [NSMutableArray array];
// 遍历 汽车品牌数组carGroups,让把标题放入arrayM中
for (CZCarGroup *carGroup in self.carGroups) {
[arrayM addObject:carGroup.title];
}
索引效果如图: