SwiftUI中如何为AppDelegate添加可访问的UIWindow属性?
解决SwiftUI中自定义AppDelegate的
window属性访问问题 方案1:直接通过自定义AppDelegate实例访问window
你已经通过@UIApplicationDelegateAdaptor持有了自定义MyAppDelegate的实例,可直接在App结构体或其他场景中通过该实例访问window:
@main struct YourApp: App { @UIApplicationDelegateAdaptor(MyAppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() .onAppear { // 直接访问自定义delegate的window let targetWindow = appDelegate.window } } } } class MyAppDelegate: NSObject, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 按需初始化window window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIHostingController(rootView: ContentView()) window?.makeKeyAndVisible() return true } }
方案2:让UIApplication.shared.delegate.window可访问自定义window
如果必须通过UIApplication.shared.delegate.window访问,可通过关联对象给UIApplicationDelegate扩展window属性,并在自定义MyAppDelegate中同步赋值:
// 扩展UIApplicationDelegate,添加关联的window属性 private var windowAssociatedKey: UInt8 = 0 extension UIApplicationDelegate { var window: UIWindow? { get { objc_getAssociatedObject(self, &windowAssociatedKey) as? UIWindow } set { objc_setAssociatedObject(self, &windowAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } class MyAppDelegate: NSObject, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIHostingController(rootView: ContentView()) window?.makeKeyAndVisible() // 将自定义window同步到shared delegate的window属性 application.delegate?.window = window return true } }
补充说明
在iOS 13+的SwiftUI生命周期中,官方推荐使用WindowGroup或Scene相关API管理窗口,而非传统AppDelegate的window属性。如果你的需求是兼容旧逻辑或特殊场景,上述方案可解决问题。
内容的提问来源于stack exchange,提问作者Nataliia.dev
相关产品推荐
相关产品推荐

