0

In my code I use below code to set the section header title of the tableview. And it works well.

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)
    -> String? {
        //return self.adHeaders[section]
        return self.headers[section]
}

I want to customize the background color of the header, so I insert below code before the above code.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor(red: 232/255.0, green: 237/255.0, blue: 242/255.0, alpha: 1.0)
    return headerView
}

As a result, the background color changes, while the title text lost.

LF00
  • 27,015
  • 29
  • 156
  • 295
  • And you may even look into [Is it possible to obtain a dynamic table view section header height using Auto Layout?](https://stackoverflow.com/q/29462331/3687801) – nayem Mar 02 '18 at 03:58

1 Answers1

2

When you implement viewForHeaderInSection, titleForHeaderInSection isn’t called at all. So you need to set the title of your header view in viewForHeaderInSection. You probably need to create a UILabel.

You must also implement heightForHeaderInSection.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank you. It works. As I don't have much experience of IOS developing. I just want to know is it the proper way to customize the header view. – LF00 Mar 02 '18 at 03:56
  • 1
    Yes, a custom header is the way to customize. – rmaddy Mar 02 '18 at 04:02