[ACCEPTED]-OS X - How can a NSViewController find its window?-cocoa-sheet

Accepted answer
Score: 115

You can use [[self view] window]

0

Score: 42

Indeed, it's self.view.window (Swift).

This may be nil in 2 viewDidLoad() and viewWillAppear(), but 1 is set properly by the time you get to viewDidAppear().

Score: 2

One issue with the other answers (i.e., just 9 looking at self.view.window) is that they don't take into 8 account the case that when a view is hidden, its 7 window property will be nil. A view might be hidden 6 for a lot of reasons (for example, it might 5 be in one of the unselected views in a tab 4 view).

The following (swift) extension will 3 provide the windowController for a NSViewController by ascending the view 2 controller hierarchy, from which the window property 1 may then be examined:

public extension NSViewController {
    /// Returns the window controller associated with this view controller
    var windowController: NSWindowController? {
        return ((self.isViewLoaded == false ? nil : self.view)?.window?.windowController)
            ?? self.parent?.windowController // fallback to the parent; hidden views like those in NSTabView don't have a window
    }

}
Score: 1

If your controller can get access to the 1 NSDocument subclass, you can use -windowForSheet

Score: 0

more about Tim Closs answer :

-(void)viewDidAppear
{
    self.view.window.title = @"title-viewDidAppear"; //this only works when and after viewDidAppeer is called
}
-(void)viewWillDisappear
{
    self.view.window.title = @"title-viewWillDisappear"; //this only works before and when viewWillDisappear is called
}

0

More Related questions