首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS `UITableView` Style=Grouped 頂部空白區移除:`heightForHeaderInSection` 回傳 0.001 技巧

     編輯:程式設計綜合問答

現象

`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];
}

Swift 版本

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return .leastNonzeroMagnitude // iOS 11+ 建議
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return UIView(frame: .zero)
}

補充:`automaticallyAdjustsScrollViewInsets`

若使用 `UITableViewController`,iOS 11+ 已棄用 `automaticallyAdjustsScrollViewInsets`,改用 `contentInsetAdjustmentBehavior = .never` (於 `viewDidLoad` 設定) 避免導航列/工具列造成內容偏移。

替代方案:改用 Plain 樣式

若不需要 Grouped 視覺分組效果,直接初始化 `UITableViewStylePlain` 即無頂部空白,且效能稍佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved