1

In this example, the "hello" text is placed in the middle of the screen, as expected.

struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            Text("hello")
                .background(Color.green)
        }
        .background(Color.blue)
    }
}

But when I move Text to an extracted view, the "hello" text moves to the top left corner of the screen.

struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            ExtractedView()
        }
        .background(Color.blue)
    }
}

struct ExtractedView: View {
    var body: some View {
        Text("hello")
            .background(Color.green)
    }
}

Is this a bug, or an expected behavior I don't understand?

thedp
  • 8,350
  • 16
  • 53
  • 95

1 Answers1

2

Confirm top-left location on Xcode 12 / iOS 14. I don't think it is a bug. Actually, GeometryReader is not a container and does not (should not) have own default alignment, its purpose custom alignment, so here we are.

Possible solutions (tested with Xcode 12b3 / iOS 14):

  1. place by position
GeometryReader { geo in
    ExtractedView()
        .position(x: geo.size.width / 2, y: geo.size.height / 2)
}
  1. wrap into full-size stack container (that has default alignment)
GeometryReader { geo in
    VStack {
        ExtractedView()
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you for the confirmation. But if it's not a container, why does it behave like one in my first example? What's the difference between using something directly vs in an extracted view? – thedp Jul 29 '20 at 07:16