Home > Mobile >  How to make the width of a VStack grow based on the width of a Text
How to make the width of a VStack grow based on the width of a Text

Time:03-25

What I need is to be able to create a VStack where its width grows if the Text inside grows. I also would like to be able to maintain the VStack minimum width at 180pt if possible.

The following code does almost what I need except it doesn't have a minimum width; which I can live without. The issue with the code below is that I'm getting a purple warning when I test it on a device.

Any idea why am I getting the warning below?

Bye the way, I get no errors, just the warning.

struct GeneralTest: View {
    var body: some View {
        VStack{
            Text("244GGDD")
                .frame(width: .infinity, height: 55, alignment: .center)
                .font(Font.system(size: 42, weight: .light))
                .foregroundColor(Color.blue)
                .padding(.leading, 20)
                .padding(.trailing, 20)

        }
        .frame(width:.infinity, height: 100, alignment: .center)
        .background(Color.gray)
    }
}

Warning:

enter image description here

CodePudding user response:

The following modifiers should give you what you need:

Text("244GGDD")
    .fixedSize(horizontal: false, vertical: true)
    .frame(minWidth: 180)
    // other modifiers

The VStack should wrap the whole text, which will be minimum 180 points wide.

CodePudding user response:

.inifinity is for the frame with maxWidth.

width has to be finite, a number of some kind.

Try

.frame(maxWidth: .infinity, idealHeight: 55, alignment: .center)
  • Related