2

I'm trying to layout two UILabel in a horizontal UIStackView but I can't get it to work. As you can see label2 (red) is not using the remaining width from label1.

enter image description here

Here's code you can add in a Playground:

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .green

let labelStackView = UIStackView()

labelStackView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
labelStackView.frame = view.bounds

view.addSubview(labelStackView)

labelStackView.distribution = .equalSpacing
labelStackView.alignment = .lastBaseline
labelStackView.spacing = 10

let label1 = UILabel()
label1.backgroundColor = .blue
label1.numberOfLines = 0
label1.text = "Hej Hej Hej"

let label2 = UILabel()
label2.backgroundColor = .red
label2.numberOfLines = 0
label2.text = "Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej"
label2.textAlignment = .right

labelStackView.addArrangedSubview(label1)
labelStackView.addArrangedSubview(label2)

PlaygroundPage.current.liveView = view
Peter Warbo
  • 11,136
  • 14
  • 98
  • 193
  • I'm not sure about Stackview but It would be possible without Stackview, if you are looking for solution. NSLayoutConstraint with compression priority can help to achieve this result. Even you can design it using interface view without a single line of code. – Krunal Dec 01 '17 at 14:57
  • 1
    Have you played with the compression resistance of the two label views? – mschmidt Dec 01 '17 at 15:44

1 Answers1

2

As commenters have pointed out you'll need to adjust the content hugging or compression resistance of the labels as they will default to the same value causing auto layout to give them equal priority and spacing. You'll also need to change the distribution of your stack view to fillProportionally. The following worked for me:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .green

let labelStackView = UIStackView()

labelStackView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
labelStackView.frame = view.bounds

view.addSubview(labelStackView)

labelStackView.distribution = .fillProportionally
labelStackView.alignment = .lastBaseline
labelStackView.spacing = 10

let label1 = UILabel()
label1.backgroundColor = .blue
label1.numberOfLines = 0
label1.text = "Hej Hej Hej"
label1.setContentHuggingPriority(UILayoutPriority(1000), for: .horizontal)

let label2 = UILabel()
label2.backgroundColor = .red
label2.numberOfLines = 0
label2.text = "Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej"
label2.textAlignment = .right

labelStackView.addArrangedSubview(label1)
labelStackView.addArrangedSubview(label2)

PlaygroundPage.current.liveView = view
beyowulf
  • 15,101
  • 2
  • 34
  • 40