1. Empty custom view implementation
I created an empty subclass of UITableViewHeaderFooterView
as follows:
class MyCustomHeaderView: UITableViewHeaderFooterView {
}
I registered that class with my table view:
tableView.register(MyCustomHeaderView.self, forHeaderFooterViewReuseIdentifier: "myHeaderView")
and implemented the data source functions as follows:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "myHeaderView")
return headerView
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Hello"
}
As expected, this is what I get: A header view that looks just like the system default.
2. Custom view implementation that overrides drawRect(_:)
Now the reason why I implemented this subclass in the first place is because I want to perform some custom drawing. Thus, I implement the drawRect(_:)
method:
class MyCustomHeaderView: UITableViewHeaderFooterView {
override func draw(_ rect: CGRect) {
super.draw(rect)
}
}
Again I do nothing inside this method other than calling the super
implementation. So from my point of view this should not change anything because if I don't implement it the super
implementation is called anyway.
However, when I now launch the app this is what I get:
The header view's background is completely filled with a solid black color.
Why?
Additional information:
I've done some research and read several posts that recommended to set the header view's isOpaque
property to false
. I did that and I even set it for the header view's backgroundView
and contentView
— with no effect.
However, I checked in the Debug View Hierarchy in Xcode that it's actually MyCustomHeaderView
itself that's black, not its subviews, and that view is actually opaque — even though I explicitly set it to false
in code.
(As you can see from the screenshots I tried this with a brand new project, specifically with the default Xcode master-detail template, to exclude the possibility that my custom table view might be causing this.)