1

I have UIStackView

let sv = UIStackView()
sv.axis = .horizontal
sv.distribution = .fillProportionally
sv.spacing   = 2.0
sv.translatesAutoresizingMaskIntoConstraints = false

Now I have added two elements (UIView and UILabel). If I run app, I have see something like this:

| Content (UIView)|           Content (UILabel)|

But I want it like this:

| Content (UIView)           | Content (UILabel)|

How to do this?

My code for setting stack view:

let lb = UILabel()
lb.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light)
lb.lineBreakMode = .byTruncatingTail
lb.numberOfLines = 2
lb.textAlignment = .right
lb.backgroundColor = UIColor.red
lb.adjustsFontSizeToFitWidth = true


let v = UIView()


stackView.addArrangedSubview(v)
stackView.addArrangedSubview(lb)
self.contentView.addSubview(stackView)


NSLayoutConstraint.activate([
   stackView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 2),
   stackView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10),
   stackView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10),
   stackView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -2)
])   
Martin Perry
  • 9,232
  • 8
  • 46
  • 114

1 Answers1

1

Just set content compression resistance priority to 1000 for view's horizontal axis

v.setContentCompressionResistancePriority(.required, for: .horizontal)

... then your view should take as much space as it needs because it won't be compressed

Robert Dresler
  • 10,580
  • 2
  • 22
  • 40