NSLayoutConstraint - 两项,一行,间距优先

NSLayoutConstraint - Two items, one line, spacing priority

我在一行上有两个标签。我需要第二个标签紧靠第一个标签的末端,但我需要确保第二个标签永远不会超出屏幕边缘。

因此,我将 label1 的左锚点与容器视图的左侧对齐,并将 label2 的左锚点约束在 label1 的右侧,将 label2 的右锚点约束在容器的右侧。

我希望 label1 只占用它需要的 space,而 label2 占用剩余的 space。我的正好相反

所以我需要与我这里的完全相反的东西。我该怎么做?

为左侧标签提供更高的内容拥抱优先级应该可以解决问题。

// In code
leftLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)

为了进一步阅读该主题,我发现 this 非常有帮助

游乐场示例

//: A UIKit based Playground for presenting user interface
  
import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let leftLabel = UILabel()
        leftLabel.text = "I am left"
        leftLabel.backgroundColor = .orange
        leftLabel.translatesAutoresizingMaskIntoConstraints = false
        
        let rightLabel = UILabel()
        rightLabel.text = "I am right"
        rightLabel.backgroundColor = .yellow
        rightLabel.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(leftLabel)
        view.addSubview(rightLabel)
        
        leftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
        leftLabel.trailingAnchor.constraint(equalTo: rightLabel.leadingAnchor).isActive = true
        leftLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 16).isActive = true
        
        // This is the important part
        leftLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        
        rightLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
        rightLabel.topAnchor.constraint(equalTo: leftLabel.topAnchor).isActive = true
        
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()