Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding unlimited lines in a Text (SwiftUI)

Tags:

ios

swift

swiftui

Just figuring out how I can achieve multiple lines of text in a Text. It seems like the Text has the same default as UILabel (one line), but I can't find any function which meets this criteria.

struct ContentView : View {     var body: some View {         VStack(alignment: .leading, spacing: 10) {             HStack {                 Text("Avocado Toast").font(.system(size: 24))             }             // This Text does cut, and I wonder how I can achieve multiple rows             Text("Ingredients: Avocado, Almond Butter, Bread")                 .font(.system(size: 20))          }     } } 

Edit

.lineLimit(X), did the trick. But is it possible to not set a specific amount, for instance. With just a 0?

like image 974
Jacob Ahlberg Avatar asked Jun 06 '19 18:06

Jacob Ahlberg


People also ask

How do I set the number of lines in a text in SwiftUI?

To force text to have minimum n lines, you append n-1 new line characters to your text. And you should limit the number of lines to n with . lineLimit(_:) .

Is text a view in SwiftUI?

Text in SwiftUI is a view that lets you display one or more lines of text. This is suitable for read-only information that's not editable. To display a line of text, you initialize Text and set a String value.

How do I change the line height in SwiftUI?

SwiftUI text does not provide a lineHeight property (line spacing is a different beast). You could try to align the 'firstTextBaseLine' to get the desired behaviour. Alternatively, use a 'UILabel' (via 'UIViewRepresentable') with an attributed string (specify line height in the paragraph style).

How do I change the font in SwiftUI?

Hold the command key and click the text to bring up a pop-over menu. Choose Show SwiftUI Inspector and then you can edit the text/font properties.


1 Answers

For wrapping Text in a Form .lineLimit(Int.max) did not work for me. It seems there needs to be some width for it to know when to wrap. I believe the official way is with .fixedSize:

Text(message)     .fixedSize(horizontal: false, vertical: true) 

The documentation states:

This example shows the effect of fixedSize(horizontal:vertical:) on a text view that is wider than its parent, preserving the ideal, untruncated width of the text view.

https://developer.apple.com/documentation/swiftui/view/fixedsize(horizontal:vertical:)

like image 184
Michael Ozeryansky Avatar answered Sep 17 '22 11:09

Michael Ozeryansky