如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
swift 5 +
在willDisplayHeaderView方法中
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//For Header Background Color
view.tintColor = .black
// For Header Text Color
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = .white
}
我希望这对你有所帮助:]
其他回答
下面是如何更改文本颜色。
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];
In iOS 7.0.4 I created a custom header with it's own XIB. Nothing mentioned here before worked. It had to be the subclass of the UITableViewHeaderFooterView to work with the dequeueReusableHeaderFooterViewWithIdentifier: and it seems that class is very stubborn regarding the background color. So finally I added an UIView (you could do it either with code or IB) with name customBackgroudView, and then set it's backgroundColor property. In layoutSubviews: I set that view's frame to bounds. It work with iOS 7 and gives no glitches.
// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView
// in MyTableHeaderView.h
@property (nonatomic, weak) IBOutlet UIView * customBackgroundView;
// in MyTableHeaderView.m
-(void)layoutSubviews;
{
[super layoutSubviews];
self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
...
UIView * customBackgroundView = [[UIView alloc] init];
[self.contentView addSubview:customBackgroundView];
_customBackgroundView = customBackgroundView;
...
}
// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
MyTableHeaderView * header = [self.tableView
dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"];
header.customBackgroundView.backgroundColor = [UIColor redColor];
return header;
}
你可以在main上做。故事板大约2秒。
选择表视图 转到属性检查器 列表项 向下滚动到查看子标题 改变“背景”
我有一个项目使用静态表视图单元格,在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];
对我来说,在浪费了2个小时后,以上这些都不起作用,这就是解决方案。在我的情况下,它是自定义视图,但我不能改变它从storyboard和视图的awakeFromNib出于某种原因。
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = .white
}