如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
iOS 13> swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){视图。tintColor = UIColor。红}
其他回答
以下解决方案适用于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()
}
对我来说,在浪费了2个小时后,以上这些都不起作用,这就是解决方案。在我的情况下,它是自定义视图,但我不能改变它从storyboard和视图的awakeFromNib出于某种原因。
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = .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
效果好极了!
这是一个老问题,但我认为答案需要更新。
此方法不涉及定义和创建您自己的自定义视图。 在ios6及以上版本中,你可以通过定义属性轻松更改背景颜色和文本颜色
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
节委托方法
例如:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
摘自我的帖子: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/
Swift 3 / 4
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.red
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
}
只需要改变头视图图层的颜色
- (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 }