换行符不适用于tableFooterView中的UILabel

时间:2020-03-27 10:35:51

标签: ios swift uitableview uilabel tablefooterview

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

在ViewController的 render() { return ( <div className="col-2 nav-bar"> <div className="row title"> <Link to="/">MyAgenda</Link> </div> <div className="row element"> <Link to="/">Home</Link> </div> <div className="row element"> <Link to="/tasks">Tasks</Link> </div> <div className="row sub-element"> School </div> <div className="row element"> <Link to="/projects">Projects</Link> </div> <div className="row sub-element"> Personal Agenda </div> </div> ) } 中,我像这样分配tableFooterView:

viewDidLoad

let footerView = MyFooterView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 0)) tableView.tableFooterView = footerView 是带有单个标签的UIView。标签设置如下所示:

MyFooterView

为了使AutoLayout与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) ]) 一起使用,我在UIViewControllers MyFooterView内部调用此方法:

viewDidLayoutSubviews

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

tableFooterView

我该怎么办,以使标签具有多行?借助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 } } 方法,自动版式可以正常工作了。唯一的事情是标签的高度只能达到一行。

1 个答案:

答案 0 :(得分:1)

HERE是实现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
    }
}

上面的代码。

结果将是:

enter image description here