如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
对于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;
}
在我的例子中,它是这样工作的:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
希望UITableViewDelegate协议中的这个方法能让你开始:
objective - c:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
if (section == integerRepresentingYourSectionOfInterest)
[headerView setBackgroundColor:[UIColor redColor]];
else
[headerView setBackgroundColor:[UIColor clearColor]];
return headerView;
}
迅速:
func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.redColor()
} else {
headerView.backgroundColor = UIColor.clearColor()
}
return headerView
}
2017年更新:
斯威夫特3:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.red
} else {
headerView.backgroundColor = UIColor.clear
}
return headerView
}
替换[UIColor redColor]与任何你想要的UIColor。您可能还希望调整headerView的尺寸。
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
}
我希望这对你有所帮助:]
斯威夫特4
要更改UITableView Section的头视图的背景颜色、文本标签颜色和字体,只需覆盖你的表视图的willDisplayHeaderView,如下所示:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.backgroundView?.backgroundColor = .white
header.textLabel?.textColor = .black
header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
}
这对我来说非常有效;希望它也能帮助到你!