UIViewController.View.Window is null in ViewDidLoad method
Asked Answered
S

4

23

Regardless on which controller type (UIViewController, UITableViewController), the following line always yields null in the ViewDidLoad method:

this.View.Window

Is this behavior normal, or am I doing something odd? What could lead to UIViewController.View.Window being null?

(I suppose this question concerns not only MonoTouch, but also 'normal' Objective-C Cocoa).

(MonoTouch 5.2.11, Xcode 4.2.1 4D502)

Seigneury answered 23/4, 2012 at 9:47 Comment(0)
C
37

According to the documentation of UIView, the window property is nil if the view has not yet been added to a window which is the case when viewDidLoad is called.

Celik answered 23/4, 2012 at 9:52 Comment(2)
What method is called after the view is added to a window?Viceroy
@AlexRyan You can use -viewDidAppear.Suneya
A
8

self.view.window will be available in viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
    print(self.view.window)
    let vc = self.storyboard?.instantiateViewController(identifier: "SecondViewController") as? SecondViewController
    self.view.window?.rootViewController = vc
}
Ables answered 17/1, 2020 at 12:40 Comment(0)
P
5

Instead of self.view.window use

[(YourAppDelegate *)[[UIApplication sharedApplication] delegate] window]
Practical answered 23/10, 2013 at 17:2 Comment(1)
It's a problem if you are using UIScene.Weariful
W
0

If using UIScene you can get the window from viewWillAppear like this:

    func windowByParent(vc: UIViewController) -> UIWindow? {
        var window: UIWindow? = nil
        var parent: UIViewController? = vc
        
        while parent != nil && window == nil {
            window = parent?.view.window
            parent = parent?.parent
        }
        return window
    }
Wally answered 25/1 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.