如何在 iOS 14 @main 文件中获取 UIWindow 值? [英] How to get UIWindow value in iOS 14 @main file?

查看:58
本文介绍了如何在 iOS 14 @main 文件中获取 UIWindow 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过以下实现访问 didFinishLaunchingWithOptions.但是,我需要 UIWindow 变量.我不知道如何得到它.我正在使用 Xcode 12 测试版.iOS14,SwiftUI 生命周期.

<预><代码>导入 SwiftUI@主要的struct SSOKit_DemoApp:应用{@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegatevar主体:一些场景{窗口组{内容视图()}}}类 AppDelegate: NSObject, UIApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) ->布尔{打印(你好世界!!!")返回真}}

解决方案

从 iOS 13 开始,可以安全地假设获取关键窗口引用的正确方法是通过 UIWindowSceneDelegate.

@main结构演示应用程序:应用程序{变量窗口:UIWindow?{守卫让场景 = UIApplication.shared.connectedScenes.first,让 windowSceneDelegate = scene.delegate 作为?UIWindowSceneDelegate,让窗口 = windowSceneDelegate.window else {返回零}返回窗口}[...]}

I can able to access didFinishLaunchingWithOptions by below implementation. But, I need UIWindow variable. I don't know how to get it. I'm using Xcode 12 beta. iOS14, SwiftUI lifecycle.


import SwiftUI

@main
struct SSOKit_DemoApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        print("hello world!!!")
        return true
    }
}

解决方案

From iOS 13 onwards, it's safe to assume that the correct way to obtain a reference to the key window is via UIWindowSceneDelegate.

@main
struct DemoApp: App {
    
    var window: UIWindow? {
        guard let scene = UIApplication.shared.connectedScenes.first,
              let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
              let window = windowSceneDelegate.window else {
            return nil
        }
        return window
    }

    [...]
}

这篇关于如何在 iOS 14 @main 文件中获取 UIWindow 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆