`UITableViewStyleGrouped` 預設頂部有一段約 35pt 的空白區 (Section Header)。設定 `tableView:heightForHeaderInSection:` 回傳 `0` 無效,回傳 `1` 則高度變 1pt。
iOS 內部對 Grouped 樣式的 Section Header 有**最小高度限制** (約 0.5pt)。回傳 `0` 會被視為「使用預設高度」;需回傳 **大於 0 且小於最小限制** 的值 (如 `0.001` / `CGFloat.leastNonzeroMagnitude`),才會真正壓縮至近乎 0。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 0.001f; // 或 CGFLOAT_MIN / CGFloat.leastNonzeroMagnitude
}
// 同理移除底部 Footer 空白
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0.001f;
}
// 可選:移除 Section Header/Footer 視圖
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [[UIView alloc] initWithFrame:CGRectZero];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
return [[UIView alloc] initWithFrame:CGRectZero];
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return .leastNonzeroMagnitude // iOS 11+ 建議
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView(frame: .zero)
}
若使用 `UITableViewController`,iOS 11+ 已棄用 `automaticallyAdjustsScrollViewInsets`,改用 `contentInsetAdjustmentBehavior = .never` (於 `viewDidLoad` 設定) 避免導航列/工具列造成內容偏移。
若不需要 Grouped 視覺分組效果,直接初始化 `UITableViewStylePlain` 即無頂部空白,且效能稍佳。