A blog about Swift and iOS tricks

Dynamic UITableView Header Resizing

Dealing with dynamic sizing of table view is a bit quirky this is an easy way to implement a variable height header.

extension UITableView {
    func resizeHeaderToFit() {
        guard let header = tableHeaderView else { return }
        let newSize = header.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        if newSize.height != header.frame.height {
            header.frame.size.height = newSize.height
            tableHeaderView = header
        }
    }
}

// Usage
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableView.resizeHeaderToFit()
}