Edward Hung Edward Hung - 10 months ago 56
iOS Question

Get a reference to Xib File

I have a tableView with custom table section header loaded from my tableSectionHeader.xib file through the following method

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

let nib = UINib(nibName: "TableSectionHeader", bundle: nil)
discoverTableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: "TableSectionHeader")

let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("TableSectionHeader") as? TableSectionHeader {
return cell

I want to have a variable table section header based on content so I need to get a reference to my xib file (which is assigned to tableSectionHeader.swift where my IBOutlets such as postImage, postDescription gets declared).

For example, I want to do something like this...

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

// get a reference to xib,
return xibref.postImage.frame.height + xibref.postDescriptionLabel.frame.height



Note. I dont want to implement estimatedRowHeight because of the apprent "bug" that causes the tableView to jump as described in this post. I did it that way and encoutered that glitch without being able to fix it other than implementing the height manually
UITableView with dynamic cell heights jumping when scrolling up after reloading cell


You should register the NIB in viewDidLoad, and at the same time you can instantiate the NIB and store the view instance in an instance variable, xibref. Then you can simplify your viewForHeaderInSection and your existing code in heightForHeaderInSection might work.

Note that in heightForHeaderInSection you may need to actually set an image / text into the view instance and ask it to layout in order to get the correct height from it.