問題
改變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,看到的還是灰色。