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?

zumzum
  • 17,984
  • 26
  • 111
  • 172

3 Answers3

10

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
aheze
  • 24,434
  • 8
  • 68
  • 125
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)
    }                
}

}

Aaban Tariq Murtaza
  • 1,155
  • 14
  • 16
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)
        }
    }
}
ylqylq001
  • 23
  • 6