-systemLayoutSizeFittingSize: returning incorrect height for tableHeaderView under iOS 8

前端 未结 6 1945
旧时难觅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 01:03

    Problem can be in non-set preferredMaxLayoutWidth. If you will set it to correct UILabel width, it will determine constraints correctly.

    You can go through all UILabel in header and set preferredMaxLayoutWidth to label width.

    Swift 3 example:

    extension UITableView {
        public func relayoutTableHeaderView() {
            if let tableHeaderView = tableHeaderView {
                let labels = tableHeaderView.findViewsOfClass(viewClass: UILabel.self)
                for label in labels {
                    label.preferredMaxLayoutWidth = label.frame.width
                }
                tableHeaderView.setNeedsLayout()
                tableHeaderView.layoutIfNeeded()
                tableHeaderView.frame.height = tableHeaderView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
                self.tableHeaderView = tableHeaderView
            }
        }
    
        public func findViewsOfClass(viewClass: T.Type) -> [T] {
            var views: [T] = []
            for subview in subviews {
                if subview is T {
                    views.append(subview as! T)
                }
                views.append(contentsOf: subview.findViewsOfClass(viewClass: T.self))
            }
            return views
        }
    }
    

    UPDATE 2:

    Also you can have problem with incorrect height calculation if you have subview with aspect ratio constraint and at the same time proportional to superview width constraint

提交回复
热议问题