Multiline label in UIStackView

后端 未结 21 2759
有刺的猬
有刺的猬 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:09

    The correct answer is here:
    https://stackoverflow.com/a/43110590/566360


    1. Embed the UILabel inside a UIView (Editor -> Embed In -> View)
    2. Use constraints to fit the UILabel to the UIView (for example, trailing space, top space, and leading space to superview constraints)

    The UIStackView will stretch out the UIView to fit properly, and the UIView will constrain the UILabel to multiple lines.

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

    For a horizontal stack view that has a UILabel as one of its views, in Interface Builder firstly set label.numberOfLines = 0. This should allow the label to have more than 1 line. This initially failed to work for me when the stack view had stackView.alignment = .fill. To make it work simply set stackView.alignment = .center. The label can now expand to multiple lines within the UIStackView.

    The Apple documentation says

    For all alignments except the fill alignment, the stack view uses each arranged view’s intrinsic​Content​Size property when calculating its size perpendicular to the stack’s axis

    Note the word except here. When .fill is used the horizontal UIStackView does NOT resize itself vertically using the arranged subviews sizes.

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

    26 November 2020, Xcode 12.2, iOS 14.2. Following works for me for vertical stack view. It works on all devices and simulators. I use storyboard and all these values are set in storyboard.

    UILabel

    Lines: 0

    UIStackView

    Alignment: Fill

    Distribution: Fill Proportionally

    UILabel is embedded in a view and pinned to all sides to UIView.

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

    For anyone who still cannot make it work. Try to set Autoshrink with a minimum Font Scale on that UILabel.

    Screenshot UILabel Autoshrink settings

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

    iOS 9+

    Call [textLabel sizeToFit] after setting the UILabel's text.

    sizeToFit will re-layout the multiline label using preferredMaxWidth. The label will resize the stackView, which will resize the cell. No additional constraints besides pinning the stack view to the content view are required.

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

    What worked for me!

    stackview: alignment: fill, distribution: fill, constraint proportional width to superview ex. 0.8,

    label: center, and lines = 0

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