2

I am not sure why, but VStack won't center images or text all of a sudden. I have tried to use the VStack(alignment:.center) but with no success.

struct ContentView: View {

    var body: some View {
        NavigationView {
          GeometryReader { geo in
           Group{
            VStack() {
                Image(systemName: "car.fill")
            }
          }
         }
       }
    }
}

My understanding is that this should center. At least all the documents say it should center.

2 Answers 2

6

It is centred in VStack but VStack is not centred in GeometryReader. You can do the following...

  GeometryReader { geo in
    VStack {
        Image(systemName: "car.fill")
    }
    .frame(width: geo.size.width, height: geo.size.height)
  }
Sign up to request clarification or add additional context in comments.

3 Comments

is there is documentation on why this seems to happen with GeometyReader? or does this happen with other things too? Should best practice alway say you should put a frame on VStack, or any object? Sorry for the questions, just wanting to understand why this answer worked.
GeometryReader does not have own alignment, it is just a free space, with 0,0 at top-left, so you can fill it as you want with whatever you want, if you want fill it completely with some alignment, make some *stack with needed alignment, if you want custom alignment in it by corrdinates, you can does that using .position of used views, etc.
My problem was not exactly this but this resolve my centering problem as well! Thanks! So I have a View with VStack only and inside an Image with two Spacer around. It seems the VStack not properly get the screen full size even with disabled statusbar and with ignored safe area!
0

Just use a HStack to center the VStack.

struct ContentView: View {

var body: some View {
    NavigationView {
      GeometryReader { geo in
       Group{
        HStack {
            Spacer()                
            VStack() {
                Image(systemName: "car.fill")
            }
            Spacer()
        }
      }
     }
   }
}

}

or

struct ContentView: View {

var body: some View {
    NavigationView {
      GeometryReader { geo in
       Group{
        VStack() {
            HStack {
                Spacer()
                Image(systemName: "car.fill")
                Spacer()
            }
        }
      }
     }
   }
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.