0

I know that GeometryReader takes all spaces available

but Why they anchored theirs contents(child views) to topLeading corner?

This is my code

struct ContentView: View {
    var body: some View {
        VStack {
            GeometryReader { proxy in
                Text("First Stack")
                .foregroundColor(.black)
                .font(.largeTitle)
            }
            .background(Color.red.opacity(0.4))
            Text("Second Stack").background(Color.blue)
        }
        .background(Color.yellow.opacity(0.5))
    }
}

and result like this

enter image description here

Text has own size, but why it anchored or aligned topLeading

Is this default behavior of GeometryReader?

I try to make it center in GeometryReader like this

struct ContentView: View {
    var body: some View {
        VStack {
            GeometryReader { proxy in
                Text("First Stack")
                .position(x: proxy.frame(in: .local).midX, y: proxy.frame(in: .local).midY)
                .foregroundColor(.black)
                .font(.largeTitle)
            }
            .background(Color.red.opacity(0.4))
            Text("Second Stack").background(Color.blue)
        }
        .background(Color.yellow.opacity(0.5))
    }
}

enter image description here

Is it right solution for center Text in GeometryReader ?

PrepareFor
  • 2,448
  • 6
  • 22
  • 36
  • All `why's` is better to ask at forums.developer.apple.com - there are Apple engineers there, I'm in doubt there is one here. – Asperi Jul 24 '20 at 04:00

1 Answers1

1

Uh, I am surprised to see that. Actually in Xcode 11.4 the default alignment for the GeometryReader is .center, however in Xcode 12 beta 3, the default alignment looks top-leading.

I have not seen any related information yet. However I can suggest wrapping Text into VStack or HStack and providing frame from proxy. It will provide better layout organization, in my opinion of course.

struct ContentView: View {
var body: some View {
    VStack {
        GeometryReader { proxy in
            VStack {
                Text("First Stack")
                    .foregroundColor(.black)
                    .font(.largeTitle)
            }
            .frame(width: proxy.size.width, height: proxy.size.height, alignment: .center)
        }
        .background(Color.red.opacity(0.4))
        Text("Second Stack").background(Color.blue)
    }
    .background(Color.yellow.opacity(0.5))
} }
Serhat
  • 76
  • 6
  • 1
    I found the answer. It was apple's bug. https://developer.apple.com/documentation/xcode-release-notes/xcode-12-beta-release-notes, "Rebuilding against the iOS 14, macOS 11, watchOS 7, and tvOS 14 SDKs changes uses of GeometryReader to reliably top-leading align the views inside the GeometryReader. This was the previous behavior, except when it wasn’t possible to detect a single static view inside the GeometryReader. (59722992) (FB7597816)" – PrepareFor Jul 27 '20 at 05:30