23

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

3
  • Are you talking about tableView header or section headers?
    – Rishab
    May 26, 2017 at 7:45
  • @Rishab My second sentence tells what I mean. Mostly it's the case when you have list of items, but in addition it has to have a huge block of info above the actual items... I've described most used "solutions" for this, and asking if we have any updates around this problem. Your answer is similar to @Pankaj. The idea is to use all content that is above items as sectionHeader which can be dynamically self-sized. But maybe there are some new cool ways to solve this issue. Anyway, thanks. May 26, 2017 at 11:09
  • Does this answer your question? Setting tableHeaderView height dynamically Aug 26, 2020 at 7:58

9 Answers 9

17

I am guessing you are talking about section headers of table view here. If that is so you can absolutely use auto layout for section headers.

Use the below two code in viewDidLoad:

tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = 36;

Now in viewForHeaderInSection: try the below code just to get an idea how things are working out. Change it according to your requirement.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label: UILabel = {
       let lb = UILabel()
        lb.translatesAutoresizingMaskIntoConstraints = false
        lb.text = "HEADER \(section) with a loooooooooooooooonnngngngngngngngng texxxxxxxxxxxxxxxxt"
        lb.textColor = .black
        lb.backgroundColor = .yellow
        lb.numberOfLines = 0
        return lb
    }()

    let header: UIView = {
        let hd = UIView()
        hd.backgroundColor = .blue
        hd.addSubview(label)
        label.leadingAnchor.constraint(equalTo: hd.leadingAnchor, constant: 8).isActive = true
        label.topAnchor.constraint(equalTo: hd.topAnchor, constant: 8).isActive = true
        label.trailingAnchor.constraint(equalTo: hd.trailingAnchor, constant: -8).isActive = true
        label.bottomAnchor.constraint(equalTo: hd.bottomAnchor, constant: -8).isActive = true
        return hd
    }()
    return header
}
14

I like the way it's done here:

• If you want to set your tableview header height dynamically based on it's content, just call self.tableView.layoutTableFooterView() right after you have set your headerView as TableViewHeader (so after self.tableView.tableHeaderView = view )

• If you need to update your tableview header height on runtime, also call self.tableView.layoutTableFooterView() right after you have updated the values of your tableview header.

(This obviously also works with tableviewFooters, though, is not to be used for sectionHeaders/Footers)

extension UITableView {

    //Variable-height UITableView tableHeaderView with autolayout
    func layoutTableHeaderView() {

        guard let headerView = self.tableHeaderView else { return }
        headerView.translatesAutoresizingMaskIntoConstraints = false

        let headerWidth = headerView.bounds.size.width
        let temporaryWidthConstraint = headerView.widthAnchor.constraint(equalToConstant: headerWidth)

        headerView.addConstraint(temporaryWidthConstraint)

        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()

        let headerSize = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
        let height = headerSize.height
        var frame = headerView.frame

        frame.size.height = height
        headerView.frame = frame

        self.tableHeaderView = headerView

        headerView.removeConstraint(temporaryWidthConstraint)
        headerView.translatesAutoresizingMaskIntoConstraints = true
    }

}

source

1
  • Unlike pretty much all of the other answers, this one actually deals with table view table header, as opposed to section headers. And it works great, thank you!
    – Lukas Petr
    Oct 27, 2023 at 9:05
14

I'm using XCode 10.3 and this is my solution worked with your second solution using table header view.

First, you would create a separating view with xib file, for example with a label inside. And you apply the constraints for this label, top, left, bottom, right to the cell's container view. And set numberOfLines = 0.
Example image
Update your awakeFromNib() function inside your view class.

override func awakeFromNib() {
    super.awakeFromNib()
    ourLabel.translatesAutoresizingMaskIntoConstraints = false
}

Second, on your viewController, setup your tableView:

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 64

Remember don't delegate this method:

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

because we set the constraints of our view already.

Finally, you return it on the delegate method

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

the view for header.

let view = UINib(nibName: String(describing: SimpleHeaderTitleView.self), bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SimpleHeaderTitleView
 view.ourLabel.text = "Your longgggg text"
 return view



Done! Check it works.

2
  • Works like charm.
    – Sk.Azad
    Aug 5, 2020 at 13:56
  • It making table view rows getting overlapped by header view Jan 5, 2021 at 17:13
11

Copied from useyourloaf.com

Swift 5.0

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    guard let headerView = tableView.tableHeaderView else {return}
    let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    if headerView.frame.size.height != size.height {
        headerView.frame.size.height = size.height
        tableView.tableHeaderView = headerView
        tableView.layoutIfNeeded()
    }
}
1
  • This doesn't work on iPhone 8/SE for some reason. It cuts off a bit at the bottom. It works on other iPhones though.
    – Junaid
    Sep 4, 2022 at 20:51
3

Step One :

From interface builder Drag a UIView and drop into

UItableView 

This view will automatically act as a UITableView Header (Mind it not section Header) . Suppose this the width of this view is 200 .If you run the UItableView This view will automatically appear as a Header .

Create a Outlet of this drag-drop View .

@property (weak, nonatomic) IBOutlet UIView *tableViewHeader; // height of this view is 200

Now my goal is increase the height of the table View header .

Step Two :

Add this method

- (void)viewDidLayoutSubviews
{
int increasedHeight = 100;
// set a frame of this view Like example 
self.tableViewHeader.frame = CGRectMake(0, 0, self.view.frame.size.width , 200 + increasedHeight );

self.tableView.tableHeaderView = self.tableViewHeader;

}

Now you tableview header height will be 300 .

2

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.

4
  • How do you handle when the content of your sectionHeader is changed? Like for example, in the sectionHeader we have UILabel, which has 0 numberOfLines, and it can even be changed in runtime. Do you call self.tableView.reloadSections...? May 26, 2017 at 7:43
  • For the time being i am just reloading the tableview, still you can use the reloadSection method. The same implementation can be achieved with collectionview as well. I have implemented it with collectionview in this app for profile Screen itunes.apple.com/nz/app/baetter-poll-on-the-go/… May 26, 2017 at 7:47
  • Approve the answer if at all it helped :) May 26, 2017 at 12:14
  • I will try it soon, but using it as sectionHeader looks like the less evil of other solutions. May 26, 2017 at 12:33
2

If you are using Interface Builder simply you check these buttons enter image description here

1

You can do that in viewDidLayoutSubviews of the UIViewController that contains your UITableView:

@IBOutlet weak var tableView: UITableView!

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Resize header view with dynamic size in UITableView
    guard let headerView = tableView.tableHeaderView else {
        return
    }
    let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    if headerView.frame.height != size.height {
        tableView.tableHeaderView?.frame = CGRect(
            origin: headerView.frame.origin,
            size: size
        )
        tableView.layoutIfNeeded()
    }
}

0

Xcode 14 + Swift 5

This is how I made it.

First step - configuring of table view for dynamic height headers usage:

In viewViewDidLoad you need to add:

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 40

This also can be done in xib/storyboard where your tableView is located instead of configuring in code:

enter image description here

Second step - creation of header view:

You need to create custom view to use as table's header. For example view with label as a subview, pinned with constraints to superview. Any view that contains some subviews that could cause it to have different height. The main thing - you should set up content of header with constraints to make it resize itself.

Third step - configuration of tableView's delegate:

In your tableView delegate implement viewForHeaderInSection method and just return configured instance of your custom header view.

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

IMPORTANT - heightForHeaderInSection method shouldn't be implemented, just don't add it.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.