Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benpackard/92beda7ea2172fdcee3991c7083b9b3c to your computer and use it in GitHub Desktop.
Save benpackard/92beda7ea2172fdcee3991c7083b9b3c to your computer and use it in GitHub Desktop.
How to manually self-size UITableView tableHeaderView/tableFooterView in iOS 11
// For the best results, your tableHeaderView/tableFooterView should be a UITableViewHeaderFooterView with your content inside the contentView.
let tableHeaderView = UITableViewHeaderFooterView()
let fittingSize = CGSize(width: tableView.bounds.width - (tableView.safeAreaInsets.left + tableView.safeAreaInsets.right), height: 0)
let size = tableHeaderView.systemLayoutSizeFitting(fittingSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
tableHeaderView.frame = CGRect(origin: .zero, size: size)
tableView.tableHeaderView = tableHeaderView
// In particular, note that we call systemLayoutSizeFitting on the contentView of the UITableViewHeaderFooterView.
// When you set this view to the tableHeaderView/tableFooterView on the table view, the table view will preserve the existing size of its frame.
// If you need to change the size, remove the tableHeaderView/tableFooterView, set a new frame on it, then re-set it on the table view again.
// Inside a UITableViewController:
private func addTableViewHeader() {
let header = UITableViewHeaderFooterView()
let label = UILabel(text: "multi\nline\ntext", font: .systemFont(ofSize: 15), textColor: .white, textAlignment: .center, numberOfLines: 0)
label.translatesAutoresizingMaskIntoConstraints = false
header.contentView.addSubview(label)
label.snp.makeConstraints { make in
make.top.bottom.equalToSuperview().inset(20)
make.left.right.equalTo(header.contentView.readableContentGuide)
}
tableView.tableHeaderView = header
resizeTableHeaderView()
}
private func resizeTableHeaderView() {
guard let header = tableView.tableHeaderView else { return }
let fittingSize = CGSize(width: tableView.bounds.width - (tableView.safeAreaInsets.left + tableView.safeAreaInsets.right), height: 0)
let size = header.systemLayoutSizeFitting(fittingSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
header.frame = CGRect(origin: .zero, size: size)
tableView.tableHeaderView = header
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { [weak self] _ in
self?.resizeTableHeaderView()
})
super.viewWillTransition(to: size, with: coordinator)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment