我有一个使用的标头数组
let sectionHeaderTitleArray = ["test1","test2","test3]
他们被显示使用
func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
现在,所有这些工作正常,但我想修改标题的背景色,使它们更可见(较深的颜色)
任何想法,如果我可以在一个简单的行中做到这一点,还是我需要使用一个自定义单元格来创建它
谢谢
更新
//number of sections and names for the table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sectionHeaderTitleArray.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
return self.tableView.backgroundColor = UIColor.lightGrayColor()
}
而不是使用
func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String?
数据源方法,可以使用
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
委托方法,并根据需要简单地自定义UIView
返回的内容。
例如,将的文本设置为UILabel
textLabel
所需的值,并将的文本设置backgroundColor
为所需的UIColor
。
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
returnedView.backgroundColor = UIColor.lightGrayColor()
let label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}
SWIFT 5
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) //set these values as necessary
returnedView.backgroundColor = .white
let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}
谢谢,但是我可以在这里使用我的部分标题数组
因此,按照我的建议,将textLabel.text属性设置为所需的节标题:)
我需要所有部分都使用相同的浅灰色
因此,将backgroundColor设置为所需的UIColor(在您的情况下为lightGrey)
将背景色直接设置为标题视图会引发运行时警告
Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.