You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:24:00