改變UITableView的headerView、footerView背景顏色

問題

改變UITableView的header、footer背景顏色,這是個很常見的問題。之前知道的一般做法是,通過實現tableView: viewForHeaderInSection:返回一個自定義的View,里面什么都不填,只設背景顏色。但是今天發現一個更簡潔的做法。

更簡潔的方法

對于iOS 6及以后的系統,實現這個新的delegate函數即可:

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}

還可以改變文字的顏色:

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *footer = (UITableViewHeaderFooterView *)view;
    [footer.textLabel setTextColor:[UIColor whiteColor]];
}

錯誤的嘗試

寫這篇文章的目的,主要是想記錄兩種錯誤的嘗試。
當看到這個Delegate函數時,第一反應是想當然地這樣做:

錯誤嘗試1

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.backgroundColor = [UIColor clearColor];
}

這樣做是無效的,無論對什么顏色都無效。

錯誤嘗試2

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *footer = (UITableViewHeaderFooterView *)view;
    footer.contentView.backgroundColor = [UIColor redColor];
}

這樣做設成不透明的顏色就沒問題。但設成clearColor,看到的還是灰色。


本文參考

UITableView - change section header color

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 改變UITableView的header、footer背景顏色,這是個很常見的問題。之前知道的一般做法是,通過實現...
    rlqs閱讀 394評論 0 0
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,229評論 4 61
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 剛剛下班回來,身體有點不舒服,四肢乏力,頭暈暈的。 明早8點半姐姐要生孩子。 現在就睡了,晚安!
    寫寫畫畫閱讀 232評論 0 0
  • 01 看《毛姆讀書筆記》,有人問毛姆:“世間的書太多,我應該讀哪些書?” 毛姆說:“你要讀那些不讀會覺得可惜的書,...
    懷左同學閱讀 18,516評論 114 738