简体   繁体   中英

UILabel breaks early inside UIStackView

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: 漏洞

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

期望的行为

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:

在此处输入图片说明

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 .

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.

Add label inside another stack view.

UIStackView
--UIStackView
  --UILabel
--UISwitch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM