Dynamic UITableView header view height using Auto Layout

From iOS 8, you can obtain 100% dynamic table view cells by simply setting the estimated row height, then layout your elements in the cell using Auto Layout. If the content increases in height, the cell will also increase in height. The same feat can be accomplished for the header view in a table view?

With this UITableView extension the answer is YES.

(Swift 4 compatible)

extension UITableView {

//Variable-height UITableView tableHeaderView with autolayout
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: 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.tableHeaderView = headerView

headerView.removeConstraints(temporaryWidthConstraints)
headerView.translatesAutoresizingMaskIntoConstraints = true

}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *