如何在tableHeaderView中放置动态多行UILabel

问题描述 投票:0回答:2

enter image description hereI创建了一个链接到名为InstructionView的UIView类的xib视图。该视图只包含一个UILabel,只限于所有方面的边距。

标签的行数为0,换行符设置为自动换行。

然后将此视图添加到stackView。然后将stackView设置为tableView的tableHeaderView。

override func viewsToAddAfterTitle() -> [UIView] {
    var views: [UIView] = []
    if let view = Bundle.main.loadNibNamed(Constants.Nibs.instructionView, owner: self, options: nil)?.first as? InstructionView {
        view.fillWithInstruction("A long text that needs more than 1 line")
        views.append(view)
        view.setNeedsLayout()
        view.layoutIfNeeded()
    }
    return views
}

func addTableHeaderView() {
    if let viewHeader: ViewHeader = Bundle.main.loadNibNamed(Constants.Nibs.viewHeader, owner: self, options: nil)?.first as? ViewHeader {
        viewHeader.setTitle(titleText: headerTitle())
        var arrangedStackSubviews: [UIView] = viewsToAddBeforeTitle()
        arrangedStackSubviews.append(viewHeader)
        arrangedStackSubviews.append(contentsOf: viewsToAddAfterTitle())
        let stack = UIStackView(arrangedSubviews: arrangedStackSubviews)
        stack.distribution = .fill
        stack.axis = NSLayoutConstraint.Axis.vertical
        stack.alignment = .fill
        stack.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tableView.tableHeaderView = stack
    }
}

加载nib时调用fillWithInstruction函数。我称之为设置标签的文本。

func fillWithInstruction(_ instruction: String) {
    instructionLabel.text = instruction
    instructionLabel.sizeToFit()
}

我尝试计算intrinsicContentSize并根据它设置标签高度的约束。我尝试将标签放在视图和/或堆栈中。

没有我尝试过的工作。如果该文本需要超过1,我希望标签显示多于1行。但是目前它总是显示1行。

swift uilabel multiline
2个回答
0
投票

创建一个UITableViewHeaderFooterView并将其与viewForHeaderInSection委托一起使用。

看看这个例子

Custom header view from xib for UITableView


0
投票

好的,这是真正的交易:

创建此扩展程序:

extension String {
func heightNeededForLabel(_ label: UILabel) -> CGFloat {
    let width = label.frame.size.width
    guard let font = label.font else {return 0}
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
    return boundingBox.height + 20
}

}

+ 20只是给它一些空间

并称之为:

func fillWithInstruction(_ instruction: String) {
    instructionLabel.text = instruction
    guard let instructionLabel = instructionLabel else {return}
    instructionLabel.addConstraint(NSLayoutConstraint(item: instructionLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 2, constant: instruction.heightNeededForLabel(instructionLabel)))

}
© www.soinside.com 2019 - 2024. All rights reserved.