0

I know how to provide a custom UITableview header and how to customize it. But I'm stuck while using UITableview with SectionTitles.

How I can change the color of the background color UITableview header and how I can change the text color of the UITableview header.

Requirment illustration can be found here.

2 Answers2

1

You can create a customView for your header with this method: I made an example view for you to customize it.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView = UIView()
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.white
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = .boldSystemFont(ofSize: 20)
        headerView.addSubview (questionLabel)
        headerView.backgroundColor = .blue
        NSLayoutConstraint.activate([
            questionLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor, constant: 0),
            questionLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 0),
            questionLabel.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: 0)
            ])

        return headerView

    }
NicolasElPapu
  • 1,612
  • 2
  • 11
  • 26
  • This solution can be used to add a customized section header. It can't be used to customize the default section when you are using `func sectionIndexTitles(for tableView: UITableView) -> [String]? { return [sectionTitles] }` of UITableviewDataSource to show indexes. – saeedbashir Oct 11 '19 at 07:29
  • if you have an array of titles for your headers you can do: i.e label.text = sectionTitles[section] – NicolasElPapu Oct 11 '19 at 13:43
0

I found the solution. This method of UITableViewDelegate can be used to customize the default section header.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = .red

        if let header = view as? UITableViewHeaderFooterView {
            header.textLabel?.textColor = .white
        }
    }