Setting tableHeaderView height dynamically

后端 未结 8 819
梦如初夏
梦如初夏 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:01

    Determining the header's frame size using

    header.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
    

    as suggested in the answers above didn't work for me when my header view consisted of a single multiline label. With the label's line break mode set to wrap, the text just gets cut off:

    Instead, what did work for me was using the width of the table view and a height of 0 as the target size:

    header.systemLayoutSizeFitting(CGSize(width: tableView.bounds.width, height: 0))
    

    Putting it all together (I prefer to use an extension):

    extension UITableView {
        func updateHeaderViewHeight() {
            if let header = self.tableHeaderView {
                let newSize = header.systemLayoutSizeFitting(CGSize(width: self.bounds.width, height: 0))
                header.frame.size.height = newSize.height
            }
        }
    }
    

    And call it like so:

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.updateHeaderViewHeight()
    }
    

提交回复
热议问题