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

Android 多 TableView 共存時指定 TableView 顯示 Header:heightForHeaderInSection 返回 0 隱藏默認 Header

     編輯:程式設計綜合問答

問題現象

同一 Controller 管理兩個 UITableView,僅需為其中一個 (tag=3) 顯示自定義 Header,另一個顯示默認空白 Header(灰色條)。

解決方案

方案一:heightForHeaderInSection 返回 CGFloat.leastNormalMagnitude (近似 0)

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 3) {
        return 45; // 自定義 Header 高度
    }
    return CGFLOAT_MIN; // 或 0.000001,返回 0 可能被系統忽略顯示默認
}

注意:返回 0 在某些 iOS 版本會被系統視為「使用默認高度」,返回極小正數可徹底隱藏。

方案二:設置 tableView.sectionHeaderHeight = 0 (全局)

// viewDidLoad 中
otherTableView.sectionHeaderHeight = 0;
otherTableView.sectionFooterHeight = 0;

但會影響該 TableView 所有 Section,若有多 Section 需區分則不適用。

方案三:viewForHeaderInSection 返回 nil (需配合 height 為 0)

- (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;
}

避坑指南

  • 同一 Delegate 管理多 TableView,**務必**以 tableView.tag 或對象地址區分邏輯。
  • heightForHeaderInSection 返回 0 行為跨版本不一致,CGFLOAT_MIN 最穩妥。
  • 自定義 Header View 復用:用字典 sectionInfoArray 緩存,避免重複創建。
  • iOS 15+ UITableView 默認 Section Header 頂部吸附,可用 tableView.sectionHeaderTopPadding = 0 關閉。

多 TableView 共存時,精確控制 Header 顯示/隱藏的關鍵在於 heightForHeaderInSection 返回極小值而非 0,配合 viewForHeaderInSection 返回 nil。

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