Skip to content

Instantly share code, notes, and snippets.

@plam4u
Created February 11, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plam4u/94d54d12429b413b439c5b9af40b56d2 to your computer and use it in GitHub Desktop.
Save plam4u/94d54d12429b413b439c5b9af40b56d2 to your computer and use it in GitHub Desktop.
extension UITableView {
/// Variable-height UITableView tableHeaderView with autolayout
///
/// Source: https://gist.github.com/marcoarment/1105553afba6b4900c10
func layoutTableHeaderView() {
guard let headerView = self.tableHeaderView else { return }
headerView.translatesAutoresizingMaskIntoConstraints = false
let headerWidth = headerView.bounds.size.width
let temporaryWidthConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "[headerView(width)]",
options: NSLayoutConstraint.FormatOptions(rawValue: UInt(0)),
metrics: ["width": headerWidth], views: ["headerView": headerView])
headerView.addConstraints(temporaryWidthConstraints)
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let headerSize = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let height = headerSize.height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
self.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