如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
如果你正在使用自定义头视图:
class YourCustomHeaderFooterView: UITableViewHeaderFooterView {
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = .white //Or any color you want
}
}
其他回答
如果你不想创建一个自定义视图,你也可以像这样改变颜色(需要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;
}
}
Swift使它变得非常简单。只需将其添加到类中,并根据需要设置颜色。
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
或者是简单的颜色
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}
Swift 5更新
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
或者是简单的颜色
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.white
}
对于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在我的项目,但它不是强制性的改变节头颜色)
仍然可以看到标题的文本。 注意,您需要调整节标题的高度。
祝你好运。
不要忘记从委托中添加这段代码,否则您的视图将被切断或在某些情况下出现在表后面,相对于您的视图/标签的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
我通过控制台日志从Xcode得到消息
[TableView]设置背景色 UITableViewHeaderFooterView已弃用。请设置自定义 带有你想要的背景颜色的UIView到backgroundView 财产。
然后我只需要创建一个新的UIView并将其作为HeaderView的背景。 这不是一个很好的解决方案,但正如Xcode所说的那样简单。