Created
February 11, 2019 16:41
-
-
Save plam4u/94d54d12429b413b439c5b9af40b56d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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