Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
zumzum Avatar asked Sep 01 '26 20:09

zumzum


1 Answers

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
like image 143
aheze Avatar answered Sep 05 '26 06:09

aheze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!