简体   繁体   中英

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

I'm trying to get the rootViewController in iOS 13 using Objective-C. 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:

Property 'window' cannot be found in forward class object 'UIWindowSceneDelegate'

But when I go to the definition of UIWindowSceneDelegate , I see a window property:

在此处输入图像描述

So what is the right way get rootViewController in iOS 13 using Objective-C?

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:

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

See, there's the UIWindowSceneDelegate . This is the forward declaration.

Read this answer to learn what the forward declaration is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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