Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Screen safe area

Tags:

swiftui

Im trying to calculate the screen safe area size in a SwiftUI app launch so I can derive component sizes from the safe area rectangle for iOS devices of different screen sizes.

UIScreen.main.bounds - I can use this at the start but it gives me the total screen and not the safe area

GeometryReader - using this I can get the CGSize of the safe area but I cant find a way to send this anywhere - tried using Notifications and simple functions both of which caused errors

Finally I tried using the .onPreferenceSet event in the initial view then within that closure set a CGSize variable in a reference file, but doing that, for some reason makes the first view initialise twice. Does anyone know a good way to get the edge insets or the safe area size at app startup?

like image 861
JohnOfIreland Avatar asked Oct 19 '25 09:10

JohnOfIreland


1 Answers

More simpler solution :

UIApplication.shared.windows.first { $0.isKeyWindow }?.safeAreaInsets.bottom

or shorter:

UIApplication.shared.windows.first?.safeAreaInsets.top
like image 127
71029 e0dad511 Avatar answered Oct 21 '25 15:10

71029 e0dad511