10

在 ShareKit 中,代码需要确定 rootViewController 的位置,以便显示模态视图。出于某种原因,代码在 iOS 5 中失败:

    // Try to find the root view controller programmically

    // Find the top window (that is not an alert view or other window)
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(topWindow in windows)
        {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }

    UIView *rootView = [[topWindow subviews] objectAtIndex:0];  
    id nextResponder = [rootView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        self.rootViewController = nextResponder;

    else
        NSAssert(NO, @"ShareKit: Could not find a root view controller.  You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");

这是命中断言。

简单地使用以下代码有什么问题?

rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

这似乎工作正常。在某些情况下会失败吗?

4

3 回答 3

28

我不确定你是否可以依赖window.rootViewControllerb/c 你不必设置它。您可以在窗口中添加一个子视图。以下似乎工作正常:

id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder];
于 2011-12-21T07:17:38.233 回答
1

快速的方法,你可以从任何地方调用它:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
public var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

它作为标准功能包含在:

https://github.com/goktugyil/EZSwiftExtensions

于 2015-11-24T04:26:46.120 回答
0

这对我有用:

UIViewController * rootViewController = (UIViewController *)[[[UIApplication.sharedApplication.keyWindow subviews] firstObject];
于 2019-05-07T16:36:28.210 回答