swiftuigeometryreaderzstack

ZStack alignment not centered when in GeometryReader?


I have the following view:

struct TestView: View {
    
    var body: some View {
        GeometryReader { geo in
            ZStack(alignment: Alignment(horizontal: .center, vertical: .center)) {
                                
                    Text("TEST TEXT")
                
            }.background(Color.red)
        }
    }
    
}

Renders this:

enter image description here

I want views in the ZStack to be centered, and that only works if I remove the GeometryReader, like so:

struct TestView: View {
    
    var body: some View {
        ZStack(alignment: Alignment(horizontal: .center, vertical: .center)) {
            
            Text("TEST TEXT")
            
        }.background(Color.red)
    }
    
}

Renders this:

enter image description here

How can I use the GeometryReader and still have content in the ZStack be centered like shown in the last render picture above? Why is GeometryReader messing with the ZStack content alignment?


Solution

  • GeometryReader's alignment keeps changing - see GeometryReader Discrepancies with Previous OS Versions. To get the normal behavior, I usually just add .frame(maxWidth: .infinity, maxHeight: .infinity).

    struct TestView: View {
        var body: some View {
            GeometryReader { geo in
                ZStack { /// no need for the custom Alignment
                    Text("TEST TEXT")
                }
                .background(Color.red)
                .frame(maxWidth: .infinity, maxHeight: .infinity) /// here!
            }
        }
    }
    

    Result:

    Text is centered