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: 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:
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)
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)
}
}