Цвет фона заголовка UITableView - PullRequest
0 голосов
/ 20 июня 2020

Есть вопросы и ответы о том, как изменить цвет фона заголовков заголовков в UITableView. Они работают, когда класс напрямую наследуется от 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)
}

}

Ответы [ 2 ]

1 голос
/ 20 июня 2020

tableView(_:viewForHeaderInSection:) - это проверка метода делегата Docs , поэтому вам нужно добавить

table.delegate = self
0 голосов
/ 21 июня 2020

Вам необходимо будет соответствовать UITableViewDelegate для titleForHeaderInSection, willDisplayHeaderView и viewForHeaderInSection.

Вам нужно будет соответствовать UITableViewDataSource для numberOfRowsInSection, cellForRowAt, numberOfRowsInSection *. ):

table.delegate = self
table.dataSource = self
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...