简体   繁体   中英

Reusing header sections in tableview

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:

  1. Create a nib.
  2. Create a custom UITableViewHeaderFooterView , named HeaderView
  3. Add a label and connect it to HeaderView
  4. Register the nib in UITableViewController 's viewDidLoad()
  5. Dequeue and return the nib in 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?

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.

因此

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM