gpt4 book ai didi

swift - 同一个 UITableViewCell 中的两个标签约束

转载 作者:行者123 更新时间:2023-11-28 13:40:44 25 4
gpt4 key购买 nike

我想在每个单元格中添加两个标签,左边的标签作为描述,右边的标签是一个类别,我正在使用 SnapKit 库来实现自动布局。

问题是我需要为描述设置一个约束,使其不超过正确的标签,以防在我设置 description.numberOfLines = 0 时描述很长,但事实并非如此工作。

let descriptionLabel = UILabel()
descriptionLabel.textColor = .black
descriptionLabel.numberOfLines = 0

let categoryLabel = UILabel()
categoryLabel.textColor = .darkGray

descriptionLabel.snp.makeConstraints {
$0.left.equalToSuperview().offset(5)
$0.top.equalToSuperview().offset(5)
$0.right.equalTo(categoryLabel.snp.left).offset(-15).priority(.high)
$0.bottom.equalToSuperview().offset(-2)
}

categoryLabel.snp.makeConstraints {
$0.right.equalToSuperview().offset(-5)
$0.top.equalToSuperview().offset(5)
}

预期的结果,描述标签不会覆盖正确的类别标签,但实际结果并非如此。

最佳答案

这应该可以修复您的布局。见

// 1: 2: 3: 

下面代码中的注释:

class TestCell: UITableViewCell {
static let identifier: String = "test_cell_identifier"

var descriptionLabel: UILabel!
var categoryLabel: UILabel!

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configure()
}

func configure() {
descriptionLabel = UILabel()
categoryLabel = UILabel()
descriptionLabel.backgroundColor = .cyan
categoryLabel.backgroundColor = .yellow

descriptionLabel.numberOfLines = 0

contentView.addSubview(descriptionLabel)
contentView.addSubview(categoryLabel)

descriptionLabel.snp.makeConstraints {
$0.left.equalToSuperview().offset(5)
$0.top.equalToSuperview().offset(5)
// 1: default priority is .required
$0.right.equalTo(self.categoryLabel.snp.left).offset(-15)
$0.bottom.equalToSuperview().offset(-2)
}

categoryLabel.snp.makeConstraints {
$0.right.equalToSuperview().offset(-5)
$0.top.equalToSuperview().offset(5)
}

// 2: prevent category label from being compressed
categoryLabel.setContentCompressionResistancePriority(.required, for: .horizontal)

// 3: prevent category label from stretching if description label is really short
categoryLabel.setContentHuggingPriority(.required, for: .horizontal)

}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

结果:

enter image description here

关于swift - 同一个 UITableViewCell 中的两个标签约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56066785/

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