Search code examples
iosuitableviewuiscrollview

UITableView header dynamic height in run-time


I know there are a lot of posts about it, but maybe in newest iOS there are some updates on this...

I think all of us had a task to create viewController that has a lot of content at the top, most of them are self-sizing, and at the very bottom it figures out that you need to show some tableView with many items...

The first solution that can be done is to use UIScrollView, and don't care about reusableCells at all.
The second is to use UITableView's headerView and adjust its height manually (or by calling systemLayoutSizeFittingSize:) each time when it is needed.
Maybe the third solution is to use UITableView and self-sized UIView separately, with having UIEdgeInsets on tableView. And depending on what object has higher "zIndex", it can bring problems with handling interactions...
The forth solution is to use whole content above the cell, like a separate cell. Not sure this is a good idea at all...

Question: Is there any new solution to this problem? I haven't dig into it for like 2 years... Maybe in new iOS there is something like reusableViews for UIScrollView... Of course, the goal is to have reusable cells, and header with using autolayout without necessity of updating its height manually...


Solution

  • 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.