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
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.