【发布时间】: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