tableHeaderView通过其内容的高度将无法正常工作

时间:2018-12-14 09:31:37

标签: ios swift uitableview autolayout constraints

我正在尝试通过放置在里面的tableHeaderView来设置UILabel的高度。但是由于某种原因,我遇到了问题,高度小于标签的内容,有时标签无法显示全文。

外观如下:

enter image description here

这是它的外观:

enter image description here

这是我的代码:

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.size.height = tableHeaderView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            self.tableHeaderView = tableHeaderView
            print(tableHeaderView.frame)
        }
    }
}

extension UIView {
    public func findViewsOfClass<T:UIView>(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
    }
}

这段代码here的资源。

2 个答案:

答案 0 :(得分:0)

您没有将行数设为零

    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
                label.numberOfLines = 0
            }
            tableHeaderView.setNeedsLayout()
            tableHeaderView.layoutIfNeeded()
            tableHeaderView.frame.size.height = tableHeaderView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            self.tableHeaderView = tableHeaderView
            print(tableHeaderView.frame)
        }
    }
}

答案 1 :(得分:0)

אותההבעיהאחי...תגידליאםפתרת 但请尝试将此标签的内容抗压缩性优先级设置为必填(1000)