How do I set a table view header view in code with Auto Layout correctly?

I have a header view composed only using Auto Layout with UIStackViews. This view is assign to the tableViewHeader of a UITableView (with style .insetGrouped).

I set these layout constraints:

NSLayoutConstraint.activate([
    headerView.topAnchor.constraint(equalTo: tableView.topAnchor),
    headerView.leadingAnchor.constraint(equalTo: tableView.layoutMarginsGuide.leadingAnchor),
    headerView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
    headerView.trailingAnchor.constraint(equalTo: tableView.layoutMarginsGuide.trailingAnchor),
])

I have two problems with this solution:

  1. The header size doesn't update if its content's size changes. (e.g. due to updated text in the labels, content size changes or other layout changes)
  2. The bottom constraint is probably wrong, but I don't know where to pin it to and it doesn't get broken by the Auto Layout engine when shown.

I fixed my first problem by reassigning the header view whenever the content size might have changed:

tableView.tableHeaderView = headerView 

However, now when I start scrolling the header view sometimes jumps to the right and back.

In summary my question is: What's the correct way to use a table view table header view with Auto Layout in code?

Thanks,
David

Hi David,

Please file a report in Feedback Assistant, so this can be followed up.

Had you considered an alternative: instead of using tableViewHeader put your header view into the first cell of the table view?

let headerView = MyHeaderView()
cell.contentView.addSubview(headerView)
headerView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    headerView.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
    headerView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
    headerView.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor),
    headerView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor)
])

Your header view then benefits from the table view’s dynamic cell sizing support. This assumes you want to scroll your header view along with the table contents.

How do I set a table view header view in code with Auto Layout correctly?
 
 
Q