Setting Tableheaderview Height Dynamically

Setting tableHeaderView height dynamically

Copied from this post. (Make sure you see it if you're looking for more details)

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

if let headerView = tableView.tableHeaderView {

let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var headerFrame = headerView.frame

//Comparison necessary to avoid infinite loop
if height != headerFrame.size.height {
headerFrame.size.height = height
headerView.frame = headerFrame
tableView.tableHeaderView = headerView
}
}
}

UITableView header dynamic height in run-time

This is how i have approached it

Using tableview
I have created the UI For the header in XIB

Now in the following delegate method

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

}

I Create a UIView for the header and calculate the height based on the content and return the same.

Now i can return the same header view from the following delegate method

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

}

Based on the section i again create a view from xib and return that view from the method.

In my case i needed only one headerview for table so i kept 2 sections and returned the headerview for section one.

How do I set the height of tableHeaderView (UITableView) with autolayout?

You need to use the UIView systemLayoutSizeFittingSize: method to obtain the minimum bounding size of your header view.

I provide further discussion on using this API in this Q/A:

How to resize superview to fit all subviews with autolayout?



Related Topics



Leave a reply



Submit