Skip to content

Instantly share code, notes, and snippets.

@asmarques
Created May 15, 2017 06:51
Show Gist options
  • Save asmarques/198527d477b529ba0921757a1cb59ef4 to your computer and use it in GitHub Desktop.
Save asmarques/198527d477b529ba0921757a1cb59ef4 to your computer and use it in GitHub Desktop.
Autosize UITableView header and footer views
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