I have a header view composed only using Auto Layout with UIStackView
s. 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:
- 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)
- 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