同一 Controller 管理兩個 UITableView,僅需為其中一個 (tag=3) 顯示自定義 Header,另一個顯示默認空白 Header(灰色條)。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (tableView.tag == 3) {
return 45; // 自定義 Header 高度
}
return CGFLOAT_MIN; // 或 0.000001,返回 0 可能被系統忽略顯示默認
}
注意:返回 0 在某些 iOS 版本會被系統視為「使用默認高度」,返回極小正數可徹底隱藏。
// viewDidLoad 中
otherTableView.sectionHeaderHeight = 0;
otherTableView.sectionFooterHeight = 0;
但會影響該 TableView 所有 Section,若有多 Section 需區分則不適用。
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (tableView.tag == 3) {
return customHeaderView;
}
return nil; // 配合 heightForHeaderInSection 返回 0.000001
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (tableView.tag == 3) return 45;
return CGFLOAT_MIN; // 隱藏 Header
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (tableView.tag != 3) return nil;
// 僅為 tag=3 構建 Header
SectionInfo *info = self.sectionInfoArray[section];
if (!info.sectionView) {
info.sectionView = [[SectionView alloc] initWithFrame:CGRectMake(0,0,tableView.bounds.size.width,45)
title:info.groupdeck.groupTitle
section:section delegate:self];
}
return info.sectionView;
}
tableView.tag 或對象地址區分邏輯。heightForHeaderInSection 返回 0 行為跨版本不一致,CGFLOAT_MIN 最穩妥。sectionInfoArray 緩存,避免重複創建。UITableView 默認 Section Header 頂部吸附,可用 tableView.sectionHeaderTopPadding = 0 關閉。多 TableView 共存時,精確控制 Header 顯示/隱藏的關鍵在於 heightForHeaderInSection 返回極小值而非 0,配合 viewForHeaderInSection 返回 nil。