gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:46:07 25 4
gpt4 key购买 nike

enter image description here我创建了一个链接到名为InstructionView 的UIView 类的xib View 。该 View 只包含一个 UILabel,该 UILabel 被限制为所有侧面的边距。

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

然后将该 View 添加到 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()
}

我尝试计算内在内容大小并据此设置标签高度的约束。我尝试将标签放置在 View 和/或堆栈中。

我尝试过的方法都不起作用。如果该文本需要多于 1 行,我希望标签显示多于 1 行。但目前它始终显示 1 行。

最佳答案

好的,这才是真正的交易:

创建此扩展:

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

}

关于swift - 如何在tableHeaderView中放置动态多行UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com