18

我正在使用 Xcode 11 (beta3) 并为 iOS 13 构建应用程序。在我的项目中,我创建了用于UIWindowSceneDelegate在 Info.plist 中声明它的委托方法。现在我可以创建多个窗口(和 UIScene)。

现在我没有一个窗口了,如何访问 rootViewController?我需要它来获取对它所拥有的对象和边界的一些引用。

在我的 AppDelegatewindow is nil和我的 ViewController (子视图控制器)实例中,我尝试使用self.view.window.rootViewController但我发现这viewDidLoad()为时过早(我认为)并且窗口仍然为零,可以工作viewDidAppear(),但我不需要每次都进行此过程视图控制器出现的时间。

这种处理应用场景的新方法的最佳实践是什么?

这是我的 AppDelegate:

func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        return true
    }

    func application(_ application: UIApplication,
                     configurationForConnecting connectingSceneSession: UISceneSession,
                     options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

我的场景委托:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // yes it's empty, I'm using storyboard
    }
4

2 回答 2

19

现在你有不止一个 rootViewController,每个场景一个。首先,您必须回答您在使用时需要哪个。

可能您想获取当前活动场景的 rootViewController 之一,然后您可以使用它:

        var rootVC:UIViewController? = nil
        if #available(iOS 13.0, *) {
            for scene in UIApplication.shared.connectedScenes {
                if scene.activationState == .foregroundActive {
                    rootVC = ((scene as? UIWindowScene)!.delegate as! UIWindowSceneDelegate).window!!.rootViewController
                    break
                }
            }
        } else {
            // Fallback on earlier versions
        }
于 2019-08-29T09:32:52.297 回答
10

您可以使用以下方式访问连接的场景:

UIApplication.shared.connectedScenes

根据Apple 文档

连接的场景是那些在记忆中并且可能正在做积极工作的场景。连接的场景可能在前景或背景中,也可能在屏幕上或屏幕外。

然后您可以遍历它们并尝试UIWindowScene从那里获取。

guard let windowScene = (scene as? UIWindowScene) else { return }
print(windowScene.windows) // This will print windows associated with the scene.

另一方面,从视图控制器中,您可以window通过以下方式访问view

self.view.window
于 2019-07-17T06:00:28.040 回答