Home > Net >  SwiftUI - Color behaves differently if I use a ScrollView instead of a VStack
SwiftUI - Color behaves differently if I use a ScrollView instead of a VStack

Time:01-23

With this code:

struct ContentView: View {
   var body: some View {
        ScrollView(.vertical) { Color.red }
    }
}

Color only has 10 points of height but with this code:

struct ContentView: View {
    var body: some View {
        VStack { Color.red }
    }
}

Color fills up all the available space (this example uses a VStack but I could have used a GeometryReader or just the color by itself).

I expected Color to fill the whole screen in both examples, I don’t get what’s happening exactly when I use the ScrollView, if I use a border modifier like this:

struct ContentView: View {
    var body: some View {
        ScrollView(.vertical) { Color.red }
        .border(.yellow)
    }
}

It draws a border around the whole safe area implying that’s the size of ScrollView, why the color doesn’t grow to be that size as well?.

Just to clarify I’m not trying to apply a background to the ScrollView and I can obviously provide a frame to Color to fill a specific size, I’m just curious because ScrollView breaks my understanding of SwiftUI, sometimes it doesn’t behave like I expect to and this is an example of that.

CodePudding user response:

  • Some Views extend to match their parent (like geometry reader)

  • Some Views extend to match their content (like Text and Color)

  • Some Views shrink to fit their child (like Stacks)

Depending on the combination of these, you will get a different behavior,

So when you put a Color in an infinite parent like a scrollView, it can not detect the size and grow as you expected and you should use the scrollViewBackground modifier.

But when you use a Color in a stack, all sizes are defined upfront.

  • Related