Setting tableHeaderView height dynamically

后端 未结 8 804
梦如初夏
梦如初夏 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
    }
    
    0 讨论(0)
  • 2020-12-01 05:17
    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            if let headerView = self.tableView.tableHeaderView {
                let headerViewFrame = headerView.frame
                let height = headerView.systemLayoutSizeFitting(headerViewFrame.size, withHorizontalFittingPriority: UILayoutPriority.defaultHigh, verticalFittingPriority: UILayoutPriority.defaultLow).height
                var headerFrame = headerView.frame
                if height != headerFrame.size.height {
                    headerFrame.size.height = height
                    headerView.frame = headerFrame
                    self.tableView.tableHeaderView = headerView
                }
            }
        }
    

    Problem in calculating label size when using horizontal or vertical fitting

    0 讨论(0)
提交回复
热议问题