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.<
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)
}
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.
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.
UILabel
in UIView
.UILabel
lines = 0.Not sure why this order of operations makes a difference, but it does.