ZStack alignment not centered when in GeometryReader?
Asked Answered
V

3

5

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?

Verb answered 6/7, 2021 at 18:44 Comment(0)
H
12

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
Honourable answered 6/7, 2021 at 18:49 Comment(2)
that works. thank you. I'll mark it as the answer once it allows me.Verb
This didn't work for me. iOs 15.5 and xCode 13.4Blida
B
0

For now(Xcode 13.4, iOS 15.5), use 'position' modifier.

struct TestingGeometryReader: View {
var body: some View {
    GeometryReader { geo in
        Text("TEST TEXT")
            .position(x: geo.frame(in: .local).midX, y: geo.frame(in: .local).midY)
    }                
}

}

Blida answered 25/7, 2022 at 9:47 Comment(0)
B
0

I have a better solution than high vote answer, you only need set padding with ZStack

struct TestView: View {
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                Text("TEST TEXT")
            }
            .background(Color.red)
            // Set padding here
            .padding(.vertical, geometry.size.height / 2)
            .padding(.horizontal, geometry.size.width / 2)
        }
    }
}
Bluefield answered 26/3, 2023 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.