SwiftUI iOS15中windows已弃用 如何改用UIWindowScene语法获取安全边距
iOS15+ 安全边距获取报错修复方案
错误原因:UIApplication.shared.windows 从iOS15开始被废弃,UIWindowScene.windows 是实例属性,不能直接通过类名调用,需要先获取当前App活跃的窗口场景实例才能调用。
方案1:最小改动适配UIKit新API
仅调整窗口获取逻辑,兼容iOS13及以上版本:
struct StackOverflow: View { var body: some View { Text("Hello, World!") .padding(.bottom, getSafeAreaBottom() ?? 15) } private func getSafeAreaBottom() -> CGFloat? { // 筛选当前前台活跃的窗口场景 let activeScene = UIApplication.shared.connectedScenes .first { $0.activationState == .foregroundActive } as? UIWindowScene return activeScene?.windows.first?.safeAreaInsets.bottom } }
方案2:纯SwiftUI原生实现(更推荐)
直接使用SwiftUI提供的安全边距环境变量,无需依赖UIKit,性能更优:
struct StackOverflow: View { // 读取系统自带的安全边距环境变量 @Environment(\.safeAreaInsets) private var safeAreaInsets var body: some View { Text("Hello, World!") .padding(.bottom, safeAreaInsets.bottom == 0 ? 15 : safeAreaInsets.bottom) } }
如果需要兼容iOS14及更早版本,可以补充以下扩展实现低版本兼容:
extension EnvironmentValues { var safeAreaInsets: EdgeInsets { self[SafeAreaInsetsKey.self] } } private struct SafeAreaInsetsKey: EnvironmentKey { static var defaultValue: EdgeInsets { let activeScene = UIApplication.shared.connectedScenes .first { $0.activationState == .foregroundActive } as? UIWindowScene return activeScene?.windows.first?.safeAreaInsets.swiftUiInsets ?? EdgeInsets() } } extension UIEdgeInsets { var swiftUiInsets: EdgeInsets { EdgeInsets(top: top, leading: left, bottom: bottom, trailing: right) } }
内容的提问来源于stack exchange,提问作者SwiftUIRookie
相关产品推荐
相关产品推荐

