Search code examples
iosswiftuitableviewuitableviewautomaticdimension

Swift - How dynamically fixed UITableViewHeaderFooterView height size?


I have just tried below lines of code, but I doesn't work correctly. I wonder that how can I provide this case for header or footer programmatically, may be using autolayout I don't know exactly which one solved my problem. I'm using xib file both of UITableViewHeaderFooterView.

If someone explain I would be great.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Dynamic sizing for the footer view
    if let footerView = tableView.tableFooterView {
        let height = footerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        var footerFrame = footerView.frame

        if height != footerFrame.size.height {
            footerFrame.size.height = height
            footerView.frame = footerFrame
            tableView.tableFooterView = footerView
        }
    }

}

Solution

  • The UITableView calculates the HeaderFooter before they displayed, you can't update that height without calling reloadData() again.

    Have you tried to use AutoLayout on those HeaderFooterViews? I would set up the view from xib with the right constraint, and then:

    self.tableView.estimatedSectionHeaderHeight = 100
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension