自定义 UITableView 的 header/Footer 背景色

425 阅读1分钟

当style为:UITableViewStylePlain

对系统 的 headerView 设置颜色,用view.backgroundColor属性无效,需要使用tintColor方可有效。

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{ 
view.tintColor=[UIColor redColor];
} 

当style为:UITableViewStyleGrouped

对系统 headerView 设置颜色,willDisplayHeaderView 方法不会被调用,此时无论是用view.backgroundColor属性或使用tintColor均无效。需要在viewForHeaderInSection 方法返回自定义的headerView,这样willDisplayHeaderView 才会回调。

1、先设置viewForHeaderInSection

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

2、再设置 willDisplayHeaderView

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    if (section==0) {
        view.backgroundColor=[UIColor redColor];
    }else if(section==1){
        view.backgroundColor=[UIColor blueColor];
    }
}