Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 932
RanLearns Avatar asked Oct 17 '25 06:10

RanLearns


1 Answers

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.

like image 51
Asperi Avatar answered Oct 19 '25 20:10

Asperi



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!