[tableView headerViewForSection] 和[tableView footerViewForSection] 都返回nil,因为代理里面的写法不对,必须使用UITableViewHeaderFooterView的写法,如下:
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
static NSString *hIdentifier = @"hIdentifier";
UITableViewHeaderFooterView *view= [tableView dequeueReusableHeaderFooterViewWithIdentifier:hIdentifier];
if(view==nil){
view = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
view.backgroundColor = [UIColor yellowColor];
for (int i=0; i<3; i++) {
UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(i*105, 0, 100, 38)];
btn.backgroundColor = [UIColor redColor];
[btn setTitle:[NSString stringWithFormat:@"header-%d",i] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:btn];
}
}
return view;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
static NSString *fIdentifier = @"hIdentifier";
UITableViewHeaderFooterView *view= [tableView dequeueReusableHeaderFooterViewWithIdentifier:fIdentifier];
if(view==nil){
view = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
view.backgroundColor = [UIColor yellowColor];
for (int i=0; i<3; i++) {
UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(i*105, 0, 100, 38)];
btn.backgroundColor = [UIColor redColor];
[btn setTitle:[NSString stringWithFormat:@"footer-%d",i] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:btn];
}
}
return view;
}
这时[tableView headerViewForSection] 和[tableView footerViewForSection] 就都可以返回正确的值了。