UITableviewCell 中的两个 UILabel 以编程方式并排排列,优先级在 swift

Two UILabels side by side in UITableviewCell programmaticaly with priories in swift

我想以编程方式并排放置 2 个标签,以强制第二个标签的全尺寸:

使用我当前的代码,根据数据,有时它可以工作,有时状态标签被压碎,有时第一个标签留在一行....

目前我有这些约束(部分作为 UITableViewCell):

NSLayoutConstraint.activate([

            /* the 2 labels */
            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
            titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: midMargin),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: sView.leadingAnchor, constant: -4),
            
            statusLabel.topAnchor.constraint(equalTo: topAnchor, constant: midMargin),
            statusLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
           
            /* the others views */
            dateLabel.topAnchor.constraint(equalTo: sView.bottomAnchor, constant: midMargin),
            dateLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
            dateLabel.leadingAnchor.constraint(greaterThanOrEqualTo: descriptionabel.trailingAnchor, constant: 4),
            
            descriptionabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: midMargin),
            descriptionabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
           
            askByTitleLabel.topAnchor.constraint(equalTo: descriptionabel.bottomAnchor, constant: midMargin),
            askByTitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
            askByTitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
            
            askByLabel.topAnchor.constraint(equalTo: askByTitleLabel.bottomAnchor, constant: .midMargin/2),
            askByLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
            askByLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
            
            docView.topAnchor.constraint(equalTo: askByLabel.bottomAnchor, constant: midMargin),
            docView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
            docView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -midMargin),
            docView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -.margin)
        ])

问题的思路?

确保 statusLabel 设置为仅 1 行。为 statusLabel:

设置拥抱和压缩阻力优先级
    statusLabel.numberOfLines = 1
    statusLabel.setContentHuggingPriority(.required, for: .horizontal)
    statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)

titleLabel.trailingAnchor 应该相对于 statusLabel.leadingAnchor:

    titleLabel.trailingAnchor.constraint(equalTo: statusLabel.leadingAnchor, constant: -4),
        

旁注:在开发布局以提供视图(和标签)对比背景颜色时非常有帮助...使在运行时很容易看到它们的框架。