SwiftUI, UIScreen.main.bounds.midY is not centered as default

399 Views Asked by At

Update: It looks like that it only happens on notch-less models. You don't need to do anything on newer models to make both swiftui and the bounds coordinate anchored on the same center.

The red star is the default center on the View. The black star is the "UIScreen midX" which is offset by the status bar I guess. Do I need to calculate the status bar height to center the black star? Thank you.

ZStack{

         Text("✧")
            .position(x: UIScreen.main.bounds.minX, y: UIScreen.main.bounds.minY)
         Text("✧")
            .foregroundColor(Color.red)
         Text("✧")
            .position(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
 }

enter image description here

1

There are 1 best solutions below

0
William Tong On

I came across the issue again. And I found that the difference between the swiftui default center point and the UIScreen.main.bounds.height/2 is different across difference device models. You need to use the GeometryReader to get the View's default center and then pass it to other subviews or UIViewRepresentalbe so that the center of other subviews could be aligned to the SwiftUI default view center.

GeometryReader{ proxy in
    
   ZStack{

       Text("✧")
          .position(x: proxy.size.width/2, y: proxy.size.height/2)
       Text("✧")
          .foregroundColor(Color.red)
      

     }
}