如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
基于@Dj的回答,使用Swift 3。这在iOS 10上运行得很好。
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
其他回答
以下解决方案适用于Swift 1.2和iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This changes the header background
view.tintColor = UIColor.blueColor()
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel.textColor = UIColor.redColor()
}
不要忘记从委托中添加这段代码,否则您的视图将被切断或在某些情况下出现在表后面,相对于您的视图/标签的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
基于@Dj的回答,使用Swift 3。这在iOS 10上运行得很好。
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
iOS 13> swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){视图。tintColor = UIColor。红}
对我来说,在浪费了2个小时后,以上这些都不起作用,这就是解决方案。在我的情况下,它是自定义视图,但我不能改变它从storyboard和视图的awakeFromNib出于某种原因。
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = .white
}