简体   繁体   English

如何使用 Objective-C 在 iOS 13 中获取 rootViewController?

[英]How to get rootViewController in iOS 13 using Objective-C?

I'm trying to get the rootViewController in iOS 13 using Objective-C.我正在尝试使用 Objective-C 获取rootViewController 13 中的 rootViewController。 I'm doing something like this:我正在做这样的事情:

for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
    UIWindowScene *windowScene = (UIWindowScene *) scene;
    UIWindowSceneDelegate *windowSceneDelegate = (UIWindowSceneDelegate *) windowScene.delegate;
    windowSceneDelegate.window = ...
}

But when I try to access the window property in windowSceneDelegate.window = (to get the rootViewController ) I get the following error:但是当我尝试访问 windowSceneDelegate.window = 中的window属性时windowSceneDelegate.window = (获取rootViewController )我收到以下错误:

Property 'window' cannot be found in forward class object 'UIWindowSceneDelegate'在前向 class object 'UIWindowSceneDelegate' 中找不到属性“窗口”

But when I go to the definition of UIWindowSceneDelegate , I see a window property:但是当我 go 定义UIWindowSceneDelegate时,我看到了window属性:

在此处输入图像描述

So what is the right way get rootViewController in iOS 13 using Objective-C?那么使用 Objective-C 在 iOS 13 中获取 rootViewController 的正确方法是什么?

Change your code to:将您的代码更改为:

for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
    if ([scene.delegate conformsToProtocol:@protocol(UIWindowSceneDelegate)]) {
        UIWindow *window = [(id<UIWindowSceneDelegate>)scene.delegate window];
    }
}

When you open the UIKit s UIWindowScene.h header file, it contains:当您打开UIKit s UIWindowScene.h header 文件时,它包含:

@class UIScreen, UIWindow, UIWindowSceneDelegate, UISceneDestructionRequestOptions, CKShareMetadata, UISceneSizeRestrictions;

See, there's the UIWindowSceneDelegate .看,有UIWindowSceneDelegate This is the forward declaration.这是前向声明。

Read this answer to learn what the forward declaration is.阅读此答案以了解前向声明是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM