SafeAreaInsets Size for SwiftUI padding

i already used .padding(.top, UIApplication.shared.windows[0].safeAreaInsets.top)

but in swiftui 3 and iOS 15 i got this warning

'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

so in new version what is the best way for getting safe area insets?

i can't use GeometryRedaer

Accepted Reply

you can use it by adapting it to your need ;)

func getSafeAreaTop()->CGFloat{

		let keyWindow = UIApplication.shared.connectedScenes

			.filter({$0.activationState == .foregroundActive})

			.map({$0 as? UIWindowScene})

			.compactMap({$0})

			.first?.windows

			.filter({$0.isKeyWindow}).first

		

		return (keyWindow?.safeAreaInsets.top)!

	}
  • Thanks(:

  • I'm attempting to use this logic for the same issue on XCode 13 and iOS 15 but keyWindow is always nil so i'm getting the "Thread 1: Swift runtime failure: force unwrapped a nil value" error. I copied and pasted the code as is but no luck. Any assistance is appreciated!

  • @jbrobinson Sorry it's late. Someone might find this useful someday. replace return (keyWindow?.safeAreaInsets.top)! with return keyWindow?.safeAreaInsets.top ?? 0 //the only difference in the original answer

Add a Comment

Replies

you can use it by adapting it to your need ;)

func getSafeAreaTop()->CGFloat{

		let keyWindow = UIApplication.shared.connectedScenes

			.filter({$0.activationState == .foregroundActive})

			.map({$0 as? UIWindowScene})

			.compactMap({$0})

			.first?.windows

			.filter({$0.isKeyWindow}).first

		

		return (keyWindow?.safeAreaInsets.top)!

	}
  • Thanks(:

  • I'm attempting to use this logic for the same issue on XCode 13 and iOS 15 but keyWindow is always nil so i'm getting the "Thread 1: Swift runtime failure: force unwrapped a nil value" error. I copied and pasted the code as is but no luck. Any assistance is appreciated!

  • @jbrobinson Sorry it's late. Someone might find this useful someday. replace return (keyWindow?.safeAreaInsets.top)! with return keyWindow?.safeAreaInsets.top ?? 0 //the only difference in the original answer

Add a Comment