我有一个我使用的标题数组

let sectionHeaderTitleArray = ["test1","test2","test3]

他们使用

func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
} 

现在所有这些都很好,但我想修改标题的背景色,使它们更可见( colored颜色 更深)

你知道我可以用简单的一行来做这件事,还是需要使用自定义单元格来创建它

谢谢

使现代化

  //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
        }

Swift相关问答推荐

Swift中可以取消的延迟任务

SwiftData查询按日期排序的项的属性数组

如何在SWIFT中轻松格式化公制和英制使用的UnitVolume

SwiftUI map 旋转

如何把多个可观测性变成一个完备性?

SWIFT计划计时器方法在时间间隔后未被调用

从Firebase播放音频文件不起作用

如何使用Duration.TimeFormatStyle以h m s格式快速格式化时间

Swiftui 无法从核心数据中获取数据

如何延迟 swift 属性 didSet 使其每秒只触发一次

如何在 switch case 模式语句中使用 Swift 文字正则表达式?

关于变量的视图的 SwiftUI 生命周期

如何确定扩展中的具体类型?

SwiftUI 中的计时器崩溃屏幕

SwiftUI:从存储在 observableObject 中的数组中删除对象时查看崩溃

在 Swift 中计算两个日期之间的差异

哪些版本的 Xcode 支持哪些版本的 Swift?

UIButton 标题左对齐问题 (iOS/Swift)

WKWebView 确实从本地文档文件夹加载资源

来自 ObservableObject 的绑定值