I want to add to my UITableView
some custom section headers, I've searched online and saw that many people are creating a UITableViewCell
subclass and registering that as a header, it sounds like a bad practice since there's a specific class for headers and footers called UITableViewHeaderFooterView
.
So I tried to do it myself, I've created a xib file and a UITableViewHeaderFooterView
subclass- called SelectedProductsSectionHeader
.
Here's how I've connected my outlets
Here's the relevant code on the UITableViewController side-
override func viewDidLoad() {
super.viewDidLoad()
let selectedProductsSectionHeaderNib = UINib(nibName: "SelectedProductsSectionHeader", bundle: nil)
tableView.register(selectedProductsSectionHeaderNib, forHeaderFooterViewReuseIdentifier: "selectedProductsHeader")
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == SectionIndex.selectedProducts{
let selectedProductsHeaderCell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "selectedProductsHeader") // throws error
guard let selectedProductsHeader = selectedProductsHeaderCell as? SelectedProductsSectionHeader else { return nil }
return selectedProductsHeader
}
return nil
}
Runtime error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'
So I tried something else, instead of setting the File's Owner to my custom class, I've set View to my custom class, and it worked.