Horizontal Stack Content Hugging

In your iOS app, you’ve got a Horizontal Stack with subviews layed out like so:

Horizontal Stack: default content hugging

override func viewDidLoad() {
    super.viewDidLoad()
    
    let loveLabel = UILabel()
    loveLabel.text = "LOVE"
    loveLabel.backgroundColor = .systemRed
    
    let kissesLabel = UILabel()
    kissesLabel.text = "Kisses"
    kissesLabel.backgroundColor = .systemYellow
    
    let xoxoLabel = UILabel()
    xoxoLabel.text = "XOXO"
    xoxoLabel.backgroundColor = .systemBlue
    
    let stack = UIStackView(arrangedSubviews: [
        loveLabel,
        kissesLabel,
        xoxoLabel,
    ])
    stack.translatesAutoresizingMaskIntoConstraints = false
    stack.axis = .horizontal
    stack.spacing = 4
    
    view.addSubview(stack)
    
    NSLayoutConstraint.activate([
        stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        stack.leftAnchor.constraint(equalToSystemSpacingAfter: view.leftAnchor, multiplier: 1),
        view.rightAnchor.constraint(equalToSystemSpacingAfter: stack.rightAnchor, multiplier: 1),
    ])
}

Hmm, a bit too much LOVE

But what if you really want is to see less of that LOVE and more of those Kisses?

The LOVE label is taking too much horizontal space: you want Kisses to be streching out as much as possible.

What we need to do is let Auto Layout know how to prioritize our views':

  • Content Hugging
  • Compression Resistance

In this case, we care about:

  • The LOVE label’s Content Hugging priority
  • On the Horizontal axis

Let’s give LOVE a high Content Hugging priority so we can smother it with our coder love:

    let loveLabel = UILabel()
    loveLabel.text = "LOVE"
    loveLabel.backgroundColor = .systemRed
    loveLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)

Horizontal Stack: content hugging love

Excellent.

By just adding a single line of code, we were able to tell Auto Layout: “Hey, I want you to prioritize hugging this content (the LOVE label) and let other views on the Horizontal axis to take up more visual space.”

Love and Kisses. XOXO ❤️