Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SwiftUI GeometryReader without affecting outer frame?

Tags:

swiftui

Is it possible to use GeometryReader in such a way that it doesn't just fill up the parent view?

As a specific example, I want to control a bottom margin using .padding(.bottom, geometry.safeAreaInsets.bottom > 0 ? 0 : 12.0). This would use the safe area as the margin on iPhone X and a custom margin on older devices.

Without the GeometryReader my view takes up space appropriate to its actual vertical size. With the reader the view takes up 1/2 the screen.

    VStack {
      Spacer()
      GeometryReader { proxy in // Lays out nicely without this...
        HStack {
          Text("Wrong")
          Spacer()
        }.border(Color.gray, width: 1)
      }

Incorrect LayoutDesired Layout

like image 535
arsenius Avatar asked Jun 10 '19 10:06

arsenius


People also ask

How do I use GeometryReader in Swiftui?

GeometryReader works by wrapping our view inside the view builder closer, it acts as a container. For accessing the frame properties, you could just wrap the view around a geometry reader and use the geometry proxy in it.

What is the purpose of GeometryReader?

GeometryReader is a view that returns a flexible preferred size to its parent layout. We can give our views sizes using GeometryReader. GeometryReader provides us the available width and height.


1 Answers

Just add the .fixedSize() modifier to your HStack. That will achieve the desired affect.

like image 133
Krames Avatar answered Oct 26 '22 11:10

Krames