Skip to content

Instantly share code, notes, and snippets.

@benpackard
benpackard / SelfSizingTableHeaderAndTableFooterViews.swift
Last active December 18, 2017 00:28 — forked from smileyborg/SelfSizingTableHeaderAndTableFooterViews.swift
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.