Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jimmyhoran/07265d65405acdfc0cef67af93020712 to your computer and use it in GitHub Desktop.
Save jimmyhoran/07265d65405acdfc0cef67af93020712 to your computer and use it in GitHub Desktop.
import UIKit
extension UITableView {
/// Layout `UITableView.headerView` with autolayout.
func layoutTableHeaderView() {
guard let headerView = tableHeaderView else { return }
layout(headerView)
self.tableHeaderView = headerView
}
/// Layout `UITableView.footerView` with autolayout.
func layoutTableFooterView() {
guard let footerView = tableFooterView else { return }
layout(footerView)
self.tableFooterView = footerView
}
private func layout(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
let width = view.bounds.size.width
let temporaryWidthConstraint = view.widthAnchor.constraint(equalToConstant: width)
view.addConstraint(temporaryWidthConstraint)
view.setNeedsLayout()
view.layoutIfNeeded()
let footerSize = view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let height = footerSize.height
var frame = view.frame
frame.size.height = height
view.frame = frame
view.removeConstraint(temporaryWidthConstraint)
view.translatesAutoresizingMaskIntoConstraints = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment