0
votes

I'm still somewhat new to SwiftUI and I'm getting a weird case that I don't fully understand. Basically, I have a VStack that contains some Text Views but also has a background View. Ideally, I'd like the background to grow in width as much as it needs to up to a point. I figure that is what the minWidth and maxWidth are for in .frame()

I started with this and it seems to be working:

struct TestView: View {
    var body: some View {
        VStack {
            Text("Title")
            Text("Message")
        }
        .background(
            Rectangle()
                .foregroundColor(Color.blue)
                .frame(minWidth: 0,
                       maxWidth: 270)
                
        )
    }
}

enter image description here

So far so good, but when I make the text big enough that it would need to wrap, this is what I get.

enter image description here

So it seems that by putting the frame around the background only makes the min/max affect that background View. If I then try to put the frame around the VStack, I get this:

struct TestView: View {
    var body: some View {
        VStack {
            Text("Title")
            Text("Message")
        }
        .frame(minWidth: 0,
               maxWidth: 270)
        .background(
            Rectangle()
                .foregroundColor(Color.blue)

                
        )
    }
}

enter image description here

Even though I don't think I have something pushing it out, it still pushes out the the full maxWidth.

I've also tried moving the frame to the Text but that gives the same result. What is the correct way to get a VStack with background to only grow with its contents up to a maxWidth?

Thank you!

1

1 Answers

0
votes

Well I'm dumb, literally right after posting I remembered something about how the order of the modifiers on a View matter.

I put the frame after the background and it worked.

struct TestView: View {
    var body: some View {
        VStack {
            Text("Title")
            Text("Message    abcdefghijklmnopqrstuvwxyz")
        }
        .background(
            Rectangle()
                .foregroundColor(Color.blue)
        )
        .frame(minWidth: 0,
               maxWidth: 270)
    }
}

enter image description here

I'll leave my question here just incase it somehow helps someone else someday.