【问题标题】:UITableView Header background colorUITableView 标题背景颜色
【发布时间】:2020-06-20 15:34:32
【问题描述】:

UITableView中如何改变Header标题的背景颜色有问答。当类直接从 UITableView 继承时,这些工作。但是,当我将 UITableView 作为 UIViewController 的子项嵌入时,更改背景颜色的相同方法似乎不起作用。

能否请您查看下面的代码并告诉我如何做到这一点?

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var table: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = "Test row"
    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section Title"
}

func numberOfSections(in tableView: UITableView) -> Int {
    1
}

// One way to change the header color
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    view.backgroundColor = .green
}

// Another way
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let vw = UIView()
    vw.backgroundColor = .red
    return vw
}

override func viewDidLoad() {
    super.viewDidLoad()
    table = UITableView(frame: CGRect(x: view.frame.maxX/3, y: view.frame.maxY/3, width: view.frame.width/2, height: view.frame.height/2))
    table.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    table.dataSource = self
    
    view.addSubview(table)
}

}

【问题讨论】:

    标签: ios swift uitableview uikit


    【解决方案1】:

    tableView(_:viewForHeaderInSection:)是委托方法检查Docs,所以需要添加

    table.delegate = self
    

    【讨论】:

    • @Sh_Khan 谢谢...啊,太简单了!对于其他,我没有将表的委托设置为 self。我需要添加行 table.delegate = self
    【解决方案2】:

    titleForHeaderInSection、willDisplayHeaderView 和 viewForHeaderInSection 需要符合 UITableViewDelegate。

    您需要符合 UITableViewDataSource 的 numberOfRowsInSection、cellForRowAt、numberOfRowsInSection。

    在你的 viewDidLoad() 中:

    table.delegate = self
    table.dataSource = self
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2011-10-07
      • 2023-03-04
      • 1970-01-01
      • 2012-09-10
      • 2013-01-03
      • 2013-07-02
      • 1970-01-01
      • 2014-09-04
      相关资源
      最近更新 更多