Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The text doesn't get wrapped in swift UI

Tags:

ios

swift

swiftui

Even After setting the .lineLimit(nil) the text doesn't get wrapped.

var body: some View {     VStack(alignment: .center) {         Text("SwiftUI is a modern way to declare user interfaces for any Apple platform. ")             .font(.title)             .color(.red)             .lineLimit(nil)         Text("Create beautiful, dynamic apps faster than ever before.")             .font(.system(size: 20))             .lineLimit(nil)     }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) } 

enter image description here

like image 811
Let's_Create Avatar asked Jun 08 '19 11:06

Let's_Create


People also ask

How do you wrap text in UILabel?

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed. If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option + return to get a line break - return alone will finish editing.

How do I show text in SwiftUI?

Text is displayed in SwiftUI using the Text view. The text can be configured in a number of ways using modifiers such as font, fontweight, padding and background. The default Text can handle multiline text and it can be modified to set how many lines to display or how to truncate the text.

How do I use labels in SwiftUI?

A label consist of text and icon. You can either use SF Symbols or a custom image for an icon. You can either use SF Symbols or a custom image for an icon. The label also has an initializer that accepts two view builders for text and image if you feel creative.


2 Answers

After spending a lot of time with an error like this, I can't be 100% certain that this is a lineLimit issue. As of writing this post, the solution I found with more complex views is the following snippet of code to prevent wrapping:

.fixedSize(horizontal: false, vertical: true)

This should prevent the interpreter from collapsing text vertically.

I hope this helps someone.

like image 153
Sharpienero Avatar answered Oct 08 '22 12:10

Sharpienero


The full solution as of Xcode 11.3 / Swift 5.1 is found across multiple answers here.

The explanation for why this is happening is found in Matteo Pacini's answer: using the predefined .font(.title), .font(.headline), etc. seems to bring the behavior that these Text views will size themselves to always ellipsize rather than wrap. However, simply switching to .body doesn't seem like the best work around.

The best workaround is found in Sharpienero's answer: add .fixedSize(horizontal: false, vertical: true) to your Text view. This tells the Text view to NOT do its custom re-sizing horizontal logic of NOT ellipsizing which causes it to follow the standard rules that we're all use to.

Thanks to both of them!

like image 41
awolf Avatar answered Oct 08 '22 12:10

awolf