UITableViewHeaderFooterView with IB

2019-02-01 07:28发布

After many years of avoiding Interface Builder like the plague I decided to give it a chance. It's not easy.

Take UITableViewHeaderFooterView for example. Like UITableViewCell, it has a contentView property. Unlike UITableViewCell, it doesn't have a template in the Interface Builder object library.

How are we supposed to use Interface Builder to create a UITableViewHeaderFooterView with the content inside contentView? The fact that registerNib:forHeaderFooterViewReuseIdentifier: exists makes me think this should be possible somehow.

8条回答
贼婆χ
2楼-- · 2019-02-01 08:26

I also experienced the deprecation warning above and an inability to set background color, etc.. Eventually, I found that according to Apple's documentation,

You can use [the UITableViewHeaderFooter] class as-is without subclassing in most cases. If you have custom content to display, create the subviews for your content and add them to the view in the contentView property.

Following that suggestion, I took these steps:

  1. I created a xib with a view that extends only UIView--not UITableViewHeaderFooter.
  2. In viewDidLoad I registered the built-in UITableViewHeaderFooter class

    tableView.registerClass(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "sectionHeader")

  3. In the viewForHeaderInSection delegate of my UITableViewController, I dequeued the header view by that identifier and checked to see if the header view already contained a subview. If not, I load my xib and add it. Then I set my text as needed.

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier("sectionHeader")!
    
    if header.contentView.subviews.count == 0 { header.contentView.addSubview(loadMyNib()) }
    
    let myView = header.contentView.subviews[0] as! MyView
    myView.label.text = "..."
    

This seems to work, leverages reuse, and does not produce any warnings.

https://developer.apple.com/library/prerelease/tvos/documentation/UIKit/Reference/UITableViewHeaderFooterView_class/index.html#//apple_ref/occ/instm/UITableViewHeaderFooterView/prepareForReuse

查看更多
Rolldiameter
3楼-- · 2019-02-01 08:26

Following workarounds enable me to drag-assign IB items to code as variables. UITableViewHeaderFooterView doesnt allow that out of the box.

  1. create a (New File/CocoaTouchClass) UITableViewHeaderFooterView .h.m.xib normally

  2. temporarily rename superclass from UITableViewHeaderFooterView to UIView. Drag-assign your UI items to code as needed, IB will assign key-value correctly, revert back to UITableViewHeaderFooterView when done.

  3. in your tableview, use registerNib: to register instead of registerClass:. prepare the rest of tableview normally (ie:dequeue).
查看更多
登录 后发表回答