0

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

}

Thanks,

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

Community
  • 1
  • 1
user172902
  • 3,541
  • 9
  • 32
  • 75
  • So you mean you want to instantiated the XIB and keep a sizing instance... – Wain Aug 08 '16 at 06:53
  • Yes. So I cant get the variables inside my xib file such as font size, frame size, labelTextcolor...etc. I could do it by looking into my xib file and see what they are, but that means if I change the height or something inside xib, I will have to change the code which is not very nice – user172902 Aug 08 '16 at 06:56

1 Answers1

0

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.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • I am not sure how to instantiate the Nib. Would you mind share some light? When I do let nib = UINib(nibName: "TableSectionHeader", bundle: nil) as! TableSectionHeader, it says this cast will always fail. So I am not sure what would be the correct way. (TableSectionHeader contains all my IBOutlets and is connected to the Xib file). I have been working on story board alot more than xib files. Thanks – user172902 Aug 08 '16 at 08:36
  • you need to use `instantiateWithOwner:options:` – Wain Aug 08 '16 at 08:54