Skip to content

Instantly share code, notes, and snippets.

@MylesCaley
Last active December 29, 2021 03:30
Show Gist options
  • Save MylesCaley/aeb7988e10cdee5c1be3b6542244abe6 to your computer and use it in GitHub Desktop.
Save MylesCaley/aeb7988e10cdee5c1be3b6542244abe6 to your computer and use it in GitHub Desktop.
size the top header dynamically for autolayout after values have been set
// MAKE SURE YOU HAVE TOP TO BOTTOM CONSTRAINTS SET ON ALL OF THE OBJECTS IN THE HEADER VIEW!!!
// better as an extension
func sizeHeaderToFit() {
if let tableViewHeader = self.tableHeaderView {
let headerView = tableViewHeader
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
self.tableHeaderView = headerView
}
}
// see: http://roadfiresoftware.com/2015/05/how-to-size-a-table-header-view-using-auto-layout-in-interface-builder
// all this is unnecessary
func layoutTableHeaderView() {
guard let headerView = tableView.tableHeaderView else { return }
headerView.translatesAutoresizingMaskIntoConstraints = false
let headerWidth = headerView.bounds.size.width;
let temporaryWidthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "[headerView(width)]", options: NSLayoutFormatOptions(rawValue: UInt(0)), metrics: ["width": headerWidth], views: ["headerView": headerView])
headerView.addConstraints(temporaryWidthConstraints)
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.tableView.tableHeaderView = headerView
headerView.removeConstraints(temporaryWidthConstraints)
headerView.translatesAutoresizingMaskIntoConstraints = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment