1
import SwiftUI

struct Test: View {
    var body: some View {
        VStack{
            Text("dklf")
        }
        .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    }
}

Why is the VStack not aligned in the middle of the Screen vertically?

enter image description here

sheldor
  • 115
  • 12
  • 2
    That is accurate, you're forgetting to account for the status bar that is being used at the top. Try disabling your status bar in the app and it should then center. – xTwisteDx May 03 '21 at 14:11
  • If you need the status bar u can subtract its size twice to the height and it will be centered. – Miguel Isla May 03 '21 at 14:21

2 Answers2

1

UIScreen.main.bounds does not account for the Safe Area, so this is what you probably wanted:

var body: some View {
    VStack{
        Text("dklf")
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}
aheze
  • 24,434
  • 8
  • 68
  • 125
Asperi
  • 228,894
  • 20
  • 464
  • 690
0

enter image description here

Ok thanks. I don't understand, why this blue border isn't at the top. If I add .statusBar(hidden: true) after the VStack, the blue border stays also there.

struct Test: View {
    var body: some View {
        VStack{
            Color.yellow
        }
        .ignoresSafeArea()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}
sheldor
  • 115
  • 12
  • To hide the status bar check this answer: https://stackoverflow.com/questions/18979837/how-to-hide-ios-status-bar – Miguel Isla May 03 '21 at 14:41