同一UITableViewCell中的两个标签约束

时间:2019-05-09 20:03:56

标签: swift autolayout snapkit

我想在每个单元格中添加两个标签,左边的标签作为描述,右边的标签是一个类别,我将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)
        }

预期结果,说明标签不会超出正确的类别标签,但实际结果并非如此。

2 个答案:

答案 0 :(得分:1)

这应该可以解决您的布局。参见

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

答案 1 :(得分:0)

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

1-做到

$0.right.equalTo(categoryLabel.snp.left).offset(-15) 

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