Setting tableHeaderView height dynamically

后端 未结 8 818
梦如初夏
梦如初夏 2020-12-01 04:16

My application creates a UITableViewController that contains a custom tableHeaderView which may have an arbitrary height. I\'ve been struggling with a way to set this header

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 05:16

    If you're still having problems with layout with the above code sample, there's a slight chance you disabled translatesAutoresizingMaskIntoConstraints on the custom header view. In that case, you need to set translatesAutoresizingMaskIntoConstraints back to true after you set the header's frame.

    Here's the code sample I'm using, and working correctly on iOS 11.

    public override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        guard let headerView = tableView.tableHeaderView else { return }
    
        let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
        var headerFrame = headerView.frame
    
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
    
            if #available(iOS 9.0, *) {
                tableView.layoutIfNeeded()
            }
        }
    
        headerView.translatesAutoresizingMaskIntoConstraints = true
    }
    

提交回复
热议问题