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.<
The correct answer is here:
https://stackoverflow.com/a/43110590/566360
UILabel
inside a UIView
(Editor -> Embed In -> View)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.
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 intrinsicContentSize 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.
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.
For anyone who still cannot make it work. Try to set Autoshrink with a minimum Font Scale on that UILabel.
Screenshot UILabel Autoshrink settings
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.
What worked for me!
stackview: alignment: fill, distribution: fill, constraint proportional width to superview ex. 0.8,
label: center, and lines = 0