UITableView提供了tableHeaderView、tableFooterView、 viewForFooterInSection、viewForHeaderInSection来为表格设置样式,它们的用法略有区别。
tableHeaderView和tableFooterView的用法相同:
1、可以为任何style的tableView设置,并且头和尾只有各一个
2、创建需要显示的view,自定义需要的显示样式
3、tableView的tableHeaderView、tableFooterView直接指向创建的view
4、设置view的frame来获取高度
注意:
tableHeaderView和tableFooterView的宽度即为tableView的宽度,自定义的view的宽度是不能改变的,所以特殊样式就需要以此为背景,在此背景view上进行设置。
viewForFooterInSection和viewForHeaderInSection的用法相同:
1、只能设置在style为UITableViewStyleGrouped的tableview中,并且每个section都有一对头尾view
2、创建的view有两种方式,一种是自定义view显示在需要的地方(每个section都显示或显示在特定的section)
3、需要用到tableView的代理方法,在此代理方法中进行设置和指向
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor redColor];
return view;
}
4、viewForFooterInSection和viewForHeaderInSection的高度也可以通过tableView的代理方法设置
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
}
还可以通过tableView的如下属性进行设置:
@property (nonatomic) CGFloat sectionHeaderHeight;
@property (nonatomic) CGFloat sectionFooterHeight;
小技巧:
有时候需要设置tableView的style为UITableViewStyleGrouped,但是每个section之间的距离都是通过如上的属性默认设置的,这个距离太大并不是我们需要的,所以可以通过设置这两个属性来缩短section的距离:
self.tableView.sectionFooterHeight = 0.1;
self.tableView.sectionHeaderHeight = 0.1;
同时,tableView的头部距离navigationItem的距离也很大,默认距离20,可以通过如下设置来缩小距离:
self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
viewForFooterInSection和viewForHeaderInSection的第二种创建方式:
和自定义的tableViewCell类似,也可以自定义section的headerView和footerView,类型和用法为:
// 注册
[tableView registerClass:nil forHeaderFooterViewReuseIdentifier:nil];
[tableView registerClass:nil forHeaderFooterViewReuseIdentifier:nil];
// 使用
[tableView dequeueReusableHeaderFooterViewWithIdentifier:nil];
// 创建
UITableViewHeaderFooterView *view = [[UITableViewHeaderFooterView alloc]
<span style="font-family:KaiTi_GB2312;"> </span>initWithReuseIdentifier:nil];