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

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


当前回答

使用UIAppearance,你可以为你的应用程序中的所有头部更改它,如下所示:

UITableViewHeaderFooterView.appearance()。backgroundColor = theme.subViewBackgroundColor

其他回答

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

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

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

下面是如何在头视图中添加图像:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
    UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];

    headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);

    [headerView addSubview:headerImage];

    return headerView;
}

使用RubyMotion / RedPotion,将其粘贴到你的桌面屏幕:

  def tableView(_, willDisplayHeaderView: view, forSection: section)
    view.textLabel.textColor = rmq.color.your_text_color
    view.contentView.backgroundColor = rmq.color.your_background_color
  end

效果好极了!

使用UIAppearance,你可以为你的应用程序中的所有头部更改它,如下所示:

UITableViewHeaderFooterView.appearance()。backgroundColor = theme.subViewBackgroundColor

我认为这段代码还不错。

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor.whiteColor()
    headerView.backgroundView = backgroundView
    headerView.textLabel.text = "hello"
    return headerView
}