换行符不适用于 tableFooterView 中的 UILabel

line breaks not working on UILabel in tableFooterView

我有一个 tableView 和一个 footerView。它应该显示一个简单的标签。

在我的 ViewController 中,在 viewDidLoad 中,我这样分配 tableFooterView:

let footerView = MyFooterView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 0))
tableView.tableFooterView = footerView

MyFooterView 是一个只有一个标签的 UIView。标签设置如下所示:

label.font = someFont
label.adjustsFontForContentSizeCategory = true
label.textColor = .black
label.numberOfLines = 0
label.text = "my super looooooong label that should break some lines but it doesn't."
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
NSLayoutConstraint.activate([
    label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 40),
    label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -40),
    label.topAnchor.constraint(equalTo: self.topAnchor, constant: 20),
    label.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20)
])

为了让 AutoLayout 与 MyFooterView 一起工作,我在 UIViewControllers 中调用了这个方法 viewDidLayoutSubviews:

func sizeFooterToFit() {
    if let footerView = self.tableFooterView {
        footerView.setNeedsLayout()
        footerView.layoutIfNeeded()

        let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        var frame = footerView.frame
        frame.size.height = height
        footerView.frame = frame

        self.tableFooterView = footerView
    }
}

问题: 标签中的行没有断开。我得到以下结果:

我该怎么做才能让标签有多行? AutoLayout 工作正常,多亏了方法 sizeFooterToFit。唯一的问题是标签高度只有一行那么高。

是实现 tableHeaderView 的方式,根据您的情况,您只需在 UIViewController class[=18 中添加以下代码=]

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

还有助手extension

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

并删除

func sizeFooterToFit() {
    if let footerView = self.tableFooterView {
        footerView.setNeedsLayout()
        footerView.layoutIfNeeded()

        let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        var frame = footerView.frame
        frame.size.height = height
        footerView.frame = frame

        self.tableFooterView = footerView
    }
}

以上代码。

结果将是: