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

使用SwiftUI在iOS 15实现分享面板 解决windows属性弃用报错问题

iOS15 SwiftUI分享面板适配方案

错误说明

你遇到的报错是因为iOS15正式弃用了UIApplication.shared.windows属性,官方要求从对应窗口场景的UIWindowScene中获取窗口列表:

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

适配代码修改

最小改动版本

直接修改原有按钮的点击逻辑,无需额外封装,适配iOS13及以上系统:

Button {
    let textoCompartido = "Hola 😀 "
    let activityVC = UIActivityViewController(activityItems: [textoCompartido], applicationActivities: nil)
    
    // iOS15+ 兼容的窗口获取逻辑
    let currentRootVC = UIApplication.shared.connectedScenes
        .filter { $0.activationState == .foregroundActive }
        .compactMap { $0 as? UIWindowScene }
        .first?.windows
        .first(where: \.isKeyWindow)?
        .rootViewController
    
    currentRootVC?.present(activityVC, animated: true)
} label: {
    // 此处放置你自定义的按钮UI
    Text("分享内容")
}

可复用扩展版本

如果项目中多个地方需要调用分享或者获取根控制器,可以把逻辑封装成UIApplication扩展,后续调用更简洁:

// 全局扩展,建议放到项目的公共扩展文件中
extension UIApplication {
    var currentRootViewController: UIViewController? {
        // 兼容iOS12及更低版本可打开下方版本判断
        // if #available(iOS 13.0, *) {
            return connectedScenes
                .filter { $0.activationState == .foregroundActive }
                .compactMap { $0 as? UIWindowScene }
                .first?.windows
                .first(where: \.isKeyWindow)?
                .rootViewController
        // } else {
        //     return windows.first?.rootViewController
        // }
    }
}

封装后原有按钮逻辑可以简化为:

Button {
    let textoCompartido = "Hola 😀 "
    let activityVC = UIActivityViewController(activityItems: [textoCompartido], applicationActivities: nil)
    UIApplication.shared.currentRootViewController?.present(activityVC, animated: true)
}

注:Swift官方编码规范推荐变量使用小驼峰命名,上述代码已将原示例中大驼峰开头的变量调整为符合规范的写法

内容的提问来源于stack exchange,提问作者Jesus M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:27:05