Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid maxWidth to be the default width?

Tags:

xcode

swiftui

I have the following code, I want the maxWidth to not affect the size of the Text when its content has a width less than 150. As you can see in the image, when I set a maxWidth of 150, the Text view starts with that value, but I only want it to be a maximum value, not the initial one.

var body: some View {
        VStack {
            HStack(alignment: .firstTextBaseline) {
                Text("text")
                    .frame(minWidth: 0, maxWidth: 150, alignment: .leading)
                    .background(.blue)
                Text("000000")
                Spacer()
                Text("text")
            }
        }
    }

preview

I do this because I want that with small texts the numbers are attached to the first Text view, but when the text is large I want a line break as shown in the image.

preview

I have tried modifying the frame with maxWidth, and minWidth set to 0, but that also does not work.

like image 205
Andrés Mendieta Avatar asked Nov 01 '25 16:11

Andrés Mendieta


1 Answers

You can add fixedSize outside of the frame modifier:

.frame(maxWidth: 150, alignment: .leading)
.fixedSize()

enter image description here

enter image description here

like image 108
jnpdx Avatar answered Nov 03 '25 08:11

jnpdx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!