Reputation: 4942
I've been searching the whole WWW for a decent solution, but most seem outdated or insufficient.
I'm struggling in simply reusing a custom UITableViewHeaderFooterView in my UITableViewController.
This is my approach:
UITableViewHeaderFooterView
, named HeaderView
HeaderView
UITableViewController
's viewDidLoad()
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int)
Custom HeaderView
class:
class HeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var customLabel: UILabel!
}
In UITableViewController
class:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "HeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "Header")
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header") as! HeaderView
headerView.customLabel.text = "This is a header section"
return headerView
}
This seems to be the approach advised by many, but I believe I'm unable to properly set the nib's owner custom class to HeaderView
(UITableViewHeaderFooterView
). When the cell is dequeued I get a fatal crash:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x60000020ebe0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key customLabel.'
I'm definitely sure I've connected the UILabel correctly to File's Owner in nib IB.
I tried changing the HeaderView
class to UIView
, but then dequeueReusableHeaderFooterView(withIdentifier: "Header") as! HeaderView
would result in a crash when forcing UITableViewHeaderFooterView to UIView.
Why is this, and what is the current way in solving this?
Upvotes: 1
Views: 1894
Reputation: 4942
I found the issue was that I set the nib - File's owner to HeaderView
and connected my customLabel
to that.
The solution was to set the nib's view class to HeaderView
and connect the label to that instead. It was also oddly necessary to put it inside a UIView.
Upvotes: 2