how to get my UIWindow using UIApplication?

前端 未结 4 1891
半阙折子戏
半阙折子戏 2020-12-25 10:21

I have only one window and I tried

UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];

but this returned nil.

I also

相关标签:
4条回答
  • 2020-12-25 10:38

    If your main window is an outlet of your AppDelegate (which should be the case), you may simply use

    MyAppDelegate* myDelegate = (((MyAppDelegate*) [UIApplication sharedApplication].delegate));
    [myDelegate.window ...]
    
    0 讨论(0)
  • 2020-12-25 10:46

    Your application's key window isn't set until [window makeKeyAndVisible] gets called in your app delegate. Your UIViewController is probably being loaded from a NIB before this call. This explains why keyWindow is returning nil.

    Luckily, your view controller doesn't need to go through UIApplication to get the window. You can just do:

    UIWindow *mWindow = self.view.window;
    
    0 讨论(0)
  • 2020-12-25 10:57

    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-25 10:59
    [[[UIApplication sharedApplication] windows] objectAtIndex:0]; // You can also check the count of this to make sure, because if there are no windows it will crash.
    
    0 讨论(0)
提交回复
热议问题