How do I set the height of tableHeaderView (UITableView) with autolayout?

后端 未结 12 1246
后悔当初
后悔当初 2020-11-27 10:23

I\'m been smashing my head against the wall with this for last 3 or 4 hours and I can\'t seem to figure it out. I have a UIViewController with a full screen UITableView insi

12条回答
  •  北海茫月
    2020-11-27 11:04

    This solution resizes the tableHeaderView and avoids infinite loop in the viewDidLayoutSubviews() method I was having with some of the other answers here:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        if let headerView = tableView.tableHeaderView {
            let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
            var headerFrame = headerView.frame
    
            // comparison necessary to avoid infinite loop
            if height != headerFrame.size.height {
                headerFrame.size.height = height
                headerView.frame = headerFrame
                tableView.tableHeaderView = headerView
            }
        }
    }
    

    See also this post: https://stackoverflow.com/a/34689293/1245231

提交回复
热议问题