1

Given the view hierarchy:

UIStackView
--UILabel
--UISwitch

The label breaks too early, even if it can be fit to a single line.

Setting numberOfLines = 1 forces the label to be laid out correctly.

How to make UILabel perform line break only when needed?

Code:

  private lazy var title: UILabel = {
    let v = UILabel()
    v.numberOfLines = 0
    return v
  }()

  private lazy var toggle = UISwitch()
  private lazy var stack = UIStackView(axis: .horizontal,
                                       distribution: .equalSpacing,
                                       alignment: .center,
                                       views: [title,
                                               toggle])
  func setupConstraints() {
    stack.snp.makeConstraints { (make) in
      make.edges.equalTo(contentView.layoutMarginsGuide)
    }
  }

Result: Bug

Setting numberOfLines = 1 gets me what I'd like to achieve, but the label looses its multi-line functionality:

Desired behavior

How to force the desired behavior without losing support for multi-line labels?

When there is a lot of horizontal space, the label gets laid out correctly no matter of the numberOfLines property:

enter image description here

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115

3 Answers3

4

Set your UISwitch's content hugging and resistance priority to 1000.

And stack view distribution and alignment to fill.

Extra Note - If you want label and switch to be top aligned, then set alignment to top.

Mansi
  • 628
  • 1
  • 8
  • 18
  • Hugging/compression resistance did the job. I went with `fill` for `distribution` and `center` for the `alignment`, the multi-line label work fine. Exactly, what I wanted, thanks. – Richard Topchii May 03 '18 at 08:40
  • Yes, hugging and compression resistance with stack views work like a charm :) – Mansi May 03 '18 at 08:43
1

In your stack view you can give a constraint to your label and switch...

1) give your label leading, top , trailing and bottom constraint. Don't give Width constraint. In trailing constraint take second item Switch.

2) give your switch trailing, top, bottom and Fix width.

Hope it Will work.

Rakesh Patel
  • 1,673
  • 10
  • 27
1

Add label inside another stack view.

UIStackView
--UIStackView
  --UILabel
--UISwitch
Kumar
  • 1,882
  • 2
  • 27
  • 44