Created
May 15, 2017 06:51
-
-
Save asmarques/198527d477b529ba0921757a1cb59ef4 to your computer and use it in GitHub Desktop.
Autosize UITableView header and footer views
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 { | |
func autoSizeHeaderAndFooter() { | |
let width = self.bounds.width | |
let autoSize = { (view: UIView) in | |
view.translatesAutoresizingMaskIntoConstraints = false | |
let widthConstraint = NSLayoutConstraint(item: view, | |
attribute: NSLayoutAttribute.width, | |
relatedBy: NSLayoutRelation.equal, | |
toItem: nil, | |
attribute: NSLayoutAttribute.notAnAttribute, | |
multiplier: 1, | |
constant: width) | |
view.addConstraint(widthConstraint) | |
let height = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height | |
view.removeConstraint(widthConstraint) | |
view.frame = CGRect(x: 0, y: 0, width: width, height: height) | |
view.translatesAutoresizingMaskIntoConstraints = true | |
} | |
if let view = tableHeaderView { | |
autoSize(view) | |
tableHeaderView = view | |
} | |
if let view = tableFooterView { | |
autoSize(view) | |
tableFooterView = view | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment