How to limit width of Text in SwiftUI

Viewed 1087

I was trying to make a speech bubble like so:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)

However I thought the speech bubble looked way wider than it needed to be. Therefore I tried to limit how far out the bubble can stretch before it goes to a new line. The easiest way which came to mind was this:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)  // << Limits how wide it can stretch

This worked for long messages but when the text was small such as "Hello," the frame would stay at 300pts and refused to resize to its ideal width.

Frame staying at 300pts

I tried using .fixedSize() but this would cause truncation when the text was long.

I couldn't find a way to cap the width of the text and still have it be its ideal size. If someone could propose a solution I would be extremely grateful.

In short: The text frame should never cross 300pts in width but it can be as tall as it wants.

Thanks in advance!

Edit

These are the things I've tried so far:

Text("Hello")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)
    .lineLimit(nil)

which causes the "Hello" bubble to have a frame of 300 (I've provided an image above)

and I've tried:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)
    .lineLimit(nil)
    .fixedSize()

which gave me:

Truncated text

0 Answers
Related