arsenius
arsenius

Reputation: 13256

Use SwiftUI GeometryReader without affecting outer frame?

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

Upvotes: 28

Views: 13544

Answers (2)

Vitaly
Vitaly

Reputation: 529

You can also try adding .aspectRatio(contentMode: .fit) modifier to GeometryReader.

Upvotes: 17

Krames
Krames

Reputation: 374

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

Upvotes: 19

Related Questions