viewWillAppear or viewDidAppear on NSWindowController

喜夏-厌秋 提交于 2019-12-04 01:40:09

Yes, there's no such convenient methods in NSWindowController. Let me explain why.
There is a difference between iOS view controller and OS X window controller: in iOS, view controller can appear fullscreen or completely hide from screen. That's all. The window in OS X has many more degrees of freedom: it can be shown, hidden, resized, minimized/restored, overlayed by other apps' windows, go fullscreen, go to another screen (in multimonitor configuration), etc. For tracking all this activity, NSWindow has a delegate (which is automatically mapped on corresponding NSWindowController in xib). Take a look at NSWindowDelegate docs. So there's no direct behavioral mapping between iOS "appear" and OS X bunch of actions. But we can try to use the nearest possible events.

For your case (do something at window become visible), I can offer 2 different methods.
First, override the showWindow action in your NSWindowController subclass:

- (IBAction)showWindow:(id)sender
{
    [super showWindow:sender];

    // your code here
}

This way, your code will be called every time window is created/shown on screen.

Or second, use the delegate method:

- (void)windowDidChangeOcclusionState:(NSNotification *)notification
{
    // notification.object is the window that changed its state.
    // It's safe to use self.window instead if you don't assign one delegate to many windows
    NSWindow *window = notification.object;

    // check occlusion binary flag
    if (window.occlusionState & NSWindowOcclusionStateVisible)  
    {
        // your code here
    }
}

This way, your code will be called every time when window (or it's part) will become visible. For example, this event can occur if user minimized the other window that was over your window (or moved it somewhere). It is usual when you want to suspend animation/timers/etc in invisible window to save some cpu :)
It's also very useful method if you need to do something on window disappear (for example, windows with enabled hidesOnDeactivate flag is not closed and does not call corresponding delegate methods; they just removed from screen without closing). This method allow us to track those situations:

- (void)windowDidChangeOcclusionState:(NSNotification *)notification
{
    if (self.window.occlusionState & NSWindowOcclusionStateVisible)
    {
        // Appear code here
    }
    else
    {
        // Disappear code here
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!