如何跟踪NSWindow的开闭事件?

时间:2010-08-18 18:44:07

标签: cocoa events

我确实试过– windowDidExpose:但是没有用。我该怎么办呢?

我的窗口是一个实用工具窗口。

- 编辑更清晰 -

我想要的是:

viewWillAppear viewWillDisappear viewDidLoad viewDidUnload

在Cocoa Touch中。

4 个答案:

答案 0 :(得分:5)

很老的问题,但仅用于文档目的:


跟踪开放: 在您的Windows控制器中覆盖方法:

-(void)showWindow:(id)sender
{
    //add this for track the window close
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowWillClose)
                                                 name:NSWindowWillCloseNotification
                                               object:nil];
    [super showWindow:sender];
    //do here what you want...
}

跟踪关闭: 实施方法

-(void)windowWillClose
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //do here what you want...
}

答案 1 :(得分:4)

windowDidClose:,但这可能仅指关闭;如果您向窗口发送orderOut:消息,我认为这不重要。

您可能需要从您为窗口输入和输出的任何代码中跟踪它,或者对窗口的类进行子类化并覆盖makeKeyAndOrderFront:orderOut:等方法(无论您是什么)至少使用)在调用super之前发布自定义通知。

答案 2 :(得分:1)

对于Swift

跟踪打开:在您的Windows控制器中覆盖方法:

override func showWindow(sender: AnyObject?) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(windowWillClose), name: NSWindowWillCloseNotification, object: nil)
    }

跟踪关闭:实施方法:

func windowWillClose() -> Void {

        NSNotificationCenter.defaultCenter().removeObserver(self);
        //Do here what you want..
    }

答案 3 :(得分:0)

我想出了一个处理这个的黑客。没有通知信号已经在屏幕上放置了一个窗口,但是当窗口被放置在屏幕上时,会发出一个非常有保证发送的通知。我说的是NSWindowDidUpdateNotification,表示窗口已经刷新了。

当然,当窗口出现时,它不会只发送 - 每次窗口更新时都会发送它。不用说,此通知不止一次发送 lot 。因此,您希望第一次观看它,做您的事情,并忽略任何后续通知。在我的情况下,我想在一个窗口中添加一个工作表,我的应用程序的另一部分将在稍后订购。所以我做了这样的事情:

__block id observer = [NSNotificationCenter.defaultCenter addObserverForName:NSWindowDidUpdateNotification object:window queue:nil usingBlock:^(NSNotification *note) {
    [self showSetupSheet];
    [NSNotificationCenter.defaultCenter removeObserver:observer];
}];

没有特别的理由你必须使用基于块的观察者 - 基于方法的观察者也可以正常工作。