如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
iOS 8 +
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
其他回答
只需要设置背景视图的背景色:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
如果有人需要斯威夫特,请保留头衔:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.addSubview(label)
return view
}
-(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 whiteColor]; // substitute your color here
content.backgroundColor = color;
[castView.textLabel setTextColor:[UIColor blackColor]];
}
}
使用UIAppearance,你可以为你的应用程序中的所有头部更改它,如下所示:
UITableViewHeaderFooterView.appearance()。backgroundColor = theme.subViewBackgroundColor
下面是如何更改文本颜色。
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];