Home > Back-end >  shrinking multiline text with maximal width in SwiftUI
shrinking multiline text with maximal width in SwiftUI

Time:07-14

Having a text that is maximum a specified width, and if the text is shorter takes up not more space is easy enough. It can be done using:

Text("Short text")
            .frame(maxWidth: UIScreen.main.bounds.width * 0.6)
            .fixedSize(horizontal: true, vertical: false)
            .lineLimit(nil)
            .border(Color.blue)

resulting in: screenshot The problem here is that if the text is too long, it will not become multiline, but it gets truncated. This could be fixed by removing the fixedSize modifier, but then the text frame no longer shrinks when the text is less wide than the maximal width. like so: second_screenshot

How can I get the shrinking AND the multiline capability if the text is too long for the maximal width?

CodePudding user response:

Wrap your text around a stack. Is this what you wanted? (code is below the image) enter image description here

struct ContentView: View {
var body: some View {
    VStack {
        
        //auto multiline if width is bigger than maxWidth
        Text("TestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTestingTesting")
            .lineLimit(nil)
            .border(Color.blue)
        
        //auto shrink if width is less than maxWidth
        Text("Testing")
            .lineLimit(nil)
            .border(Color.blue)
    }//maxWidth
    .frame(maxWidth: UIScreen.main.bounds.width * 0.6)
}
}
  • Related