如何在UITableView中改变section头的颜色?

编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。


当前回答

如果你不想创建一个自定义视图,你也可以像这样改变颜色(需要iOS 6):

-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        UIView* content = castView.contentView;
        UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
        content.backgroundColor = color;
    }
}

其他回答

对于iOS8(测试版)和Swift,选择你想要的RGB颜色,然后试试这个:

override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
    var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()

    header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
    return header

}

(“覆盖”是有,因为我' m使用UITableViewController而不是一个正常的UIViewController在我的项目,但它不是强制性的改变节头颜色)

仍然可以看到标题的文本。 注意,您需要调整节标题的高度。

祝你好运。

Although func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) will work as well, you can acheive this without implementing another delegate method. in you func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? method, you can use view.contentView.backgroundColor = UIColor.white instead of view.backgroundView?.backgroundColor = UIColor.white which is not working. (I know that backgroundView is optional, but even when it is there, this is not woking without implementing willDisplayHeaderView

对我来说,在浪费了2个小时后,以上这些都不起作用,这就是解决方案。在我的情况下,它是自定义视图,但我不能改变它从storyboard和视图的awakeFromNib出于某种原因。

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        header.contentView.backgroundColor = .white
    }

我通过控制台日志从Xcode得到消息

[TableView]设置背景色 UITableViewHeaderFooterView已弃用。请设置自定义 带有你想要的背景颜色的UIView到backgroundView 财产。

然后我只需要创建一个新的UIView并将其作为HeaderView的背景。 这不是一个很好的解决方案,但正如Xcode所说的那样简单。

在UITableViewHeaderFooterView上设置背景色已弃用。请使用contentView。写成backgroundColor代替。