SwiftUI: height and spacing of Views in GeometryReader within a ScrollView

1.2k Views Asked by At
ScrollView {
    VStack() {
        ForEach(0 ..< 5) { item in
            Text("Hello There")
                .font(.largeTitle)
         }
    }
}

The above code results in this:

enter image description here

When we add a GeometryReader, the views lose their sizing and spacing from one another (the .position modifier is just to center the text views within the GeometryReader):

ScrollView {
    VStack() {
        ForEach(0 ..< 5) { item in
            GeometryReader { geometry in
            Text("Hello There")
                .font(.largeTitle)
                .position(x: UIScreen.main.bounds.size.width/2)
            }
        }
    }
}

enter image description here

Can anybody share some help/advice around why this is the behavior and what I may want to look into in order to use a GeometryReader on center aligned views within a ScrollView as I'm trying to do here?

Adding a .frame(minHeight: 40) modifier to the ForEach is one way to force the views to take the space that the Text needs, but that is not a very nice or scalable solution.

Thank you!

1

There are 1 best solutions below

2
On

If you need just width of screen then place GeometryReader outside of scrollview:

GeometryReader { geometry in     // << here !!
  ScrollView {
    VStack() {
        ForEach(0 ..< 5) { item in
            Text("Hello There")
                .font(.largeTitle)
                .position(x: UIScreen.main.bounds.size.width/2)
            }
        }
    }
}

Can anybody share some help/advice around why this is the behavior

ScrollView does not have own size so GeometryReader cannot read anything from it and provides for own children some minimal dimension.