-systemLayoutSizeFittingSize: returning incorrect height for tableHeaderView under iOS 8

前端 未结 6 1784
旧时难觅i
旧时难觅i 2021-02-07 00:08

There are numerous threads about correctly sizing a tableHeaderView with auto-layout (one such thread) but they tend to pre-date iOS 8.

I have a situation with numerous

6条回答
  •  走了就别回头了
    2021-02-07 00:43

    Since this question is a year and a half old, here is a updated and complete version, in Swift. Some of the code from the accepted answer is wrong or outdated.

    func fixHeaderHeight() {
        // Set your label text if needed
        // ...
        //
    
        guard let header = tableView.tableHeaderView else {
            return
        }    
        let height = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        header.frame.height = height            
        tableView.tableHeaderView = header
    }
    

    Somewhere else in your code, you'll need to set the preferredMaxLayoutWidth of the label(s) in the header. This should be equal to the tableView (or screen width) minus any padding. The didSet method of your label outlet is a good place:

    @IBOutlet weak var headerMessageLabel: UILabel! {
            didSet {
                headerMessageLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - headerMessageLabelPadding
            }
        }
    

    Note: If the accepted answer worked for you, you aren't using size classes properly.

提交回复
热议问题