簡體   English   中英

換行符不適用於 tableFooterView 中的 UILabel

[英]line breaks not working on UILabel in tableFooterView

我有一個帶有footerViewtableView 它應該顯示一個簡單的標簽。

在我的 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)
])

為了獲得自動版式與工作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
    }
}

問題:標簽中的線條沒有中斷。 我得到以下結果:

表頁腳視圖

我該怎么做才能使標簽具有多行? 由於方法sizeFooterToFit AutoLayout 正在工作。 唯一的問題是標簽高度只有一行。

是您如何為tableHeaderView實現它的方法,對於您的情況,您只需要在UIViewController類中添加以下代碼

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
    }
}

以上代碼。

結果將是:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM