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

Two labels constraints in one same UITableViewCell

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

问题是我需要为描述设置一个限制条件,以防止在我设置 description.numberOfLines = 0 时描述太长,但它不起作用。

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

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

        descriptionLabel.snp.makeConstraints {
            [=10=].left.equalToSuperview().offset(5)
            [=10=].top.equalToSuperview().offset(5)
            [=10=].right.equalTo(categoryLabel.snp.left).offset(-15).priority(.high)
            [=10=].bottom.equalToSuperview().offset(-2)
        }

        categoryLabel.snp.makeConstraints {
            [=10=].right.equalToSuperview().offset(-5)
            [=10=].top.equalToSuperview().offset(5)
        }

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

高优先级意味着当描述标签文本很长时它会被破坏

1- 成功

[=10=].right.equalTo(categoryLabel.snp.left).offset(-15) 

2- 将 categoryLabel 的水平 contentCompressionResistance 设置为 1000

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

// 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 {
            [=11=].left.equalToSuperview().offset(5)
            [=11=].top.equalToSuperview().offset(5)
            // 1: default priority is .required
            [=11=].right.equalTo(self.categoryLabel.snp.left).offset(-15)
            [=11=].bottom.equalToSuperview().offset(-2)
        }

        categoryLabel.snp.makeConstraints {
            [=11=].right.equalToSuperview().offset(-5)
            [=11=].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")
    }
}

结果: