Multiline label in UIStackView

后端 未结 21 2762
有刺的猬
有刺的猬 2020-12-02 04:30

When putting multiline label (with linebreak set to Word Wrap) into a stack view, the label immediately loses the linebreak and displays the label text in one line instead.<

相关标签:
21条回答
  • 2020-12-02 05:34

    After trying all above suggestion I found no properties change is need for the UIStackView. I just change the properties of the UILabels as following (The labels are added to a vertical stack view already):

    Swift 4 example:

    [titleLabel, subtitleLabel].forEach(){
        $0.numberOfLines = 0
        $0.lineBreakMode = .byWordWrapping
        $0.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
    }
    
    0 讨论(0)
  • 2020-12-02 05:34

    The magic trick for me was to set a widthAnchor to the UIStackView.

    Setting leadingAnchor and trailingAnchor won't work, but setting centerXAnchor and widthAnchor made the UILabel display correctly.

    0 讨论(0)
  • 2020-12-02 05:35

    For those working with a storyboard or XIB file trying to embed a UILabel in a horizontal stack view, do NOT add constraints to anything that will you plan on putting in a stack view before the stack view is created. This will cause errors and/or an inability to wrap text.

    Instead, do this in addition to the suggestions made by Andy and pmb.

    1. Embed a UILabel in UIView.
    2. Set UILabel lines = 0.
    3. Create a stack view.
    4. Set the stack view alignment to top/bottom/center.
    5. Add constraints to elements within the stack view.

    Not sure why this order of operations makes a difference, but it does.

    0 讨论(0)
提交回复
热议问题