自定義 viewForHeaderInSection 返回固定高度 22pt 的 Header View,但**第一個 Section 的 Header 明顯比後續 Section 高**,視覺上佈局不整齊。
UITableView 對 **第一個 Section** 有默認的 **sectionHeaderTopPadding**(iOS 15+ 為 0,舊版本非零)及 **默認 Header 高度**(約 22-28pt,受字體/樣式影響)。若僅實現 viewForHeaderInSection 而**不實現 heightForHeaderInSection**,TableView 會用默認高度佈局第一個 Header,導致高度不一致。
// 1. 統一 Header 高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 22.0f; // 與 viewForHeaderInSection 中 UIView 的 frame 高度一致
}
// 2. 消除 Footer 佔位(可選,避免底部多餘空白)
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0.1f; // 最小非零,iOS 不允許 0
}
// 3. 你的 viewForHeaderInSection 保持不變
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// ... 創建 UILabel、UIView、設置 frame (0, 0, width, 22) ...
return sectionView;
}
iOS 15 引入 sectionHeaderTopPadding (默認 ~1-2pt),導致第一個 Section 頂部多出間距。全局關閉:
if (@available(iOS 15.0, *)) {
tableView.sectionHeaderTopPadding = 0;
}
或在 viewForHeaderInSection 返回的 View 設置 backgroundColor 為 clearColor,並在外層容器控制間距。
dequeueReusableHeaderFooterViewWithIdentifier: (需註冊 Class/Nib),複雜自定義 View 通常不復用,直接 new 即可。UITableViewStyleGrouped 預設有圓角、間距,Header/Footer 行為與 Plain 不同,按設計稿選型。「有 View 必有 Height」,牢記雙委託配對,UITableView 佈局不再塌陷。