我正在寻找一个纯粹的基于 SwiftUI 的解决方案,以根据根视图的安全区域插入来确定 iOS 设备是否具有一流的性能。虽然这在 UIKit 中很容易确定,但对于 SwiftUI,我迄今为止找到的唯一解决方案也是 UIKittish,即:
extension UIApplication {
var currentWindow: UIWindow? {
connectedScenes
.compactMap {
$0 as? UIWindowScene
}
.flatMap {
$0.windows
}
.first {
$0.isKeyWindow
}
}
}
private struct SafeAreaInsetsKey: EnvironmentKey {
static var defaultValue: EdgeInsets {
UIApplication.shared.currentWindow?.safeAreaInsets.swiftUiInsets ?? EdgeInsets()
}
}
extension EnvironmentValues {
var safeAreaInsets: EdgeInsets {
self[SafeAreaInsetsKey.self]
}
}
private extension UIEdgeInsets {
var swiftUiInsets: EdgeInsets {
EdgeInsets(top: top, leading: left, bottom: bottom, trailing: right)
}
}
虽然 SwiftUI 很可能会继续在底层使用
UIWindow
等 UIKit 元素,因此上述解决方案将在未来几年继续有效,但我仍然想知道是否有一个纯粹的基于 SwiftUI 的解决方案。
您可以从
GeometryReader
获取安全区域插图。您可以将 GeometryReader
放在视图层次结构的最顶部,也许直接放在 WindowGroup { ... }
中。然后您可以使用环境密钥发送插图。
WindowGroup {
GeometryReader { geo in
ContentView() // the rest of the app is here
.environment(\.safeAreaInsets, geo.safeAreaInsets)
}
}
private struct SafeAreaInsetsKey: EnvironmentKey {
static var defaultValue: EdgeInsets = .init()
}
extension EnvironmentValues {
var safeAreaInsets: EdgeInsets {
get { self[SafeAreaInsetsKey.self] }
set { self[SafeAreaInsetsKey.self] = newValue }
}
}