Warm tip: This article is reproduced from serverfault.com, please click

ios-使用标题数组在UITableView中更改节标题背景颜色

(ios - Change the sections header background color in UITableView using an array of headers)

发布于 2015-05-14 14:59:15

我有一个使用的标头数组

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()
    }
Questioner
Jp4Real
Viewed
0
2,531 2019-06-04 11:25:06

而不是使用

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
        }