Swift含SceneDelegate时CustomizeAlert弹窗不显示的代码修改方案咨询
解决SceneDelegate下自定义弹窗无法显示的问题
问题根源是:启用SceneDelegate的项目中,UIApplication.shared.delegate?.window会返回nil——因为窗口(UIWindow)不再由AppDelegate管理,而是归属到每个UIWindowScene实例中。原代码无法获取到有效的顶层视图控制器,导致弹窗无法添加。
修改后的代码兼容两种项目结构(有无SceneDelegate):
// 1. 获取当前活跃的窗口 var currentWindow: UIWindow? if #available(iOS 13.0, *) { currentWindow = UIApplication.shared.connectedScenes .filter({$0.activationState == .foregroundActive}) .compactMap({$0 as? UIWindowScene}) .first?.windows .filter({$0.isKeyWindow}).first } else { currentWindow = UIApplication.shared.delegate?.window?? } // 2. 找到顶层视图控制器 if var topController = currentWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // 3. 添加弹窗到顶层VC的视图 topController.view.addSubview(self) }
代码说明:
- 针对iOS 13+系统,通过
connectedScenes筛选出当前活跃的前台场景,再从中获取关键窗口(keyWindow) - 兼容iOS 13以下系统,继续使用原AppDelegate的window逻辑
- 后续获取顶层presentedViewController的逻辑和原代码一致,确保弹窗添加到最上层的视图层级中
内容的提问来源于stack exchange,提问作者Xin Lok
相关产品推荐
相关产品推荐

