UIApplication sharedApplication - keyWindow is nil?

后端 未结 4 1206
逝去的感伤
逝去的感伤 2020-12-03 16:34

I want to convert a CGPoint from my UIView to UIWindow coordinates and have realized that UIApplication keyWindow is always nil; why is this?

I have tried the

相关标签:
4条回答
  • 2020-12-03 17:07

    Try this, first get the UINavigationController handle, and then the topViewController

    let navController = window?.rootViewController as! UINavigationController
    let yourMainViewController = navController.topViewController as! ItemsViewController
    

    or

    let yourMainViewController = navController.viewControllers.first as! ItemsViewController
    
    0 讨论(0)
  • 2020-12-03 17:20

    This code was executed before [window makeKeyAndVisible]; which is inside the app delegate. So, no wonder why keyWindow was nil yet.

    0 讨论(0)
  • 2020-12-03 17:29

    Easiest way is to get the window from the app delegate instead:

    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    // Do something with the window now
    
    0 讨论(0)
  • 2020-12-03 17:30

    I noticed that after having started the Guided Access, the keyWindow property on [UIApplication sharedApplication] appears to be nil.

    It happened to me only on iOS7 when starting the Guided Access Mode for the first time after having enabled it in Settings > General > Guided Access, so the starting GAM view is actually displayed and not by-passed.

    Since this Apple API seems buggy, I solved using the following code to retrieve the window I'm looking for.

    NSArray *windows = [[UIApplication sharedApplication] windows];
    if ([windows count]) {
        return windows[0];
    }
    return nil;
    

    Instead of

    [[UIApplication sharedApplication] keyWindow];
    

    maybe you could also try using

    [[[UIApplication sharedApplication] delegate] window];
    

    as iWasRobbed pointed out but it wasn't working for me as the rootViewController property isn't reachable this way.

    0 讨论(0)
提交回复
热议问题