Skip to content

Instantly share code, notes, and snippets.

@t0rn
Last active October 17, 2022 14:51
Show Gist options
  • Save t0rn/d6806262c92a15e40155fddd3237218a to your computer and use it in GitHub Desktop.
Save t0rn/d6806262c92a15e40155fddd3237218a to your computer and use it in GitHub Desktop.
extension UITableView {
func updateTableHeaderView(with view: UIView?) {
guard
let view = view
else {
tableHeaderView = nil
return
}
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(view)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: containerView.topAnchor),
view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
view.leadingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.leadingAnchor),
view.trailingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.trailingAnchor)
])
tableHeaderView = containerView
NSLayoutConstraint.activate([
containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
containerView.topAnchor.constraint(equalTo: topAnchor),
containerView.widthAnchor.constraint(equalTo: widthAnchor)
])
tableHeaderView?.layoutIfNeeded()
tableHeaderView = self.tableHeaderView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment