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

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


当前回答

你可以这样做,如果你想头部自定义颜色。自iOS 6.0以来,这个解决方案工作得很好。

Objective - C:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

迅速:

UITableViewHeaderFooterView.appearance().tintColor = .white

其他回答

你可以这样做,如果你想头部自定义颜色。自iOS 6.0以来,这个解决方案工作得很好。

Objective - C:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

迅速:

UITableViewHeaderFooterView.appearance().tintColor = .white

使用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

效果好极了!

我认为这段代码还不错。

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
}

我有一个项目使用静态表视图单元格,在iOS 7.x。willDisplayHeaderView不会触发。但是,这个方法是可行的:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSLog(@"%s", __FUNCTION__);
    CGRect headerFrame = CGRectMake(x, y, w, h);    
    UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];  
    headerView.backgroundColor = [UIColor blackColor];

只需要改变头视图图层的颜色

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
  UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,    tableView.bounds.size.width, 30)] autorelease];
 headerView.layer.backgroundColor = [UIColor clearColor].CGColor
}