UItableView一种列表展示数据的视图,又叫数据视图。他是UIScrollView的子类,也可以实现UIScrollView相关协议,但是可能会对UITableView本身的协议函数的功能造成问题
接下来分别讲解代理函数的功能和使用方式。
1.实现代理
需要实现两个代理:
UITableViewDelegate :设置列表事件响应回调
UITableViewDataSource :设置列表展示数据
2.协议的函数
UITableView每组中的单元个数(必须实现)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)
section {
NSInteger number = [[_arrayData objectAtIndex:section] count];
return number;
}
UITableView每个单元的对象(必须实现)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
NSString *str = @"cell";
//复用单元格
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:str];;//默认样式
}
cell.textLabel.text = _arrayData[indexPath.section][indexPath.row];
//要求类型必须是UITableViewCellStyleSubtitle才能显示子标题
cell.detailTextLabel.text = @"子标题";
//左侧图片
cell.imageView.image = [UIImage imageNamed:@""];
return cell;
}
UITableView点击单元格回调
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath {
NSLog(@"%zd%zd",indexPath.section,indexPath.row);
}
3.设置区块个数
UITableView设置区块个数。如果不实现这个函数,那么默认返回1 即只有一组数据
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return _arrayData.count;
}
4.单元格高度
UITableView单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:
(NSIndexPath *)indexPath {
return 50;
}
5.每组头部标题文案
UITableView每组头部标题文案
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section {
return @"每组头部标题";
}
6.每组尾部标题文案
UITableView每组尾部标题文案
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:
(NSInteger)section {
return @"每组尾部标题";
}
7.每组头部高度
UITableView每组头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:
(NSInteger)section {
return 40;
}
8.每组尾部高度
UITableView每组尾部高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:
(NSInteger)section {
return 50;
}
9.取消选中
UITableView取消选中的情况:例如先点击第一项再点击第二项,点击第二项时,取消选中第一项的状态。
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:
(NSIndexPath *)indexPath {
NSLog(@"取消选中%zd%zd",indexPath.section,indexPath.row);
}
3.UItableView的属性和函数
1.数据视图的头部尾部视图:
可以自定义视图,然后将自定义的视图作为数据视图的头部和尾部view
_tableView.tableHeaderView = nil;
_tableView.tableFooterView = nil;
2.刷新数据视图
当数据视图的数据发生变化的时候,需要重新加载数据更新视图
[_tableView reloadData];