Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Text() wrap in SwiftUI when it is too long for the width of the device?

Tags:

swiftui

I have the following and would like the longer text to wrap

Text("Long label that needs to be able to wrap but isn't doing it yet.")
    .font(.largeTitle)
    .multilineTextAlignment(.center)
    .lineLimit(0)
like image 345
mwright Avatar asked Jun 06 '19 02:06

mwright


3 Answers

Turns out you can pass nil to the .lineLimit and it will make the Text() wrap as desired.

Text("Long label that needs to be able to wrap but isn't doing it yet.")
    .font(.largeTitle)
    .multilineTextAlignment(.center)
    .lineLimit(nil)
like image 57
mwright Avatar answered Sep 17 '22 04:09

mwright


I just tested this on the lastest XCode 11 beta, beta 7. I needed to specify a non-nil line limit and also use the padding modifier in order to achieve multiline text

Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.")
   .font(.subheadline)
   .multilineTextAlignment(.center)
   .lineLimit(3)
   .padding()
like image 42
Robert Avatar answered Sep 18 '22 04:09

Robert


Both .fixedSize and .lineLimit(nil) should work.

 Text("Label text")
        .multilineTextAlignment(.leading)
        .fixedSize(horizontal: false, vertical: true)

OR

 Text("Label text")
        .multilineTextAlignment(.leading)
        .lineLimit(nil)

.fixedSize is the preferred/suggested option from Apple to word wrap the text into next line

like image 38
Naishta Avatar answered Sep 20 '22 04:09

Naishta