识别用户何时关闭窗口(单击关闭按钮时)

问题描述 投票:0回答:3

如何识别用户何时关闭窗口?

我想在窗口关闭之前做点什么。

objective-c xcode macos cocoa nswindow
3个回答
13
投票

我在视图控制器中使用它

//initWithNibName

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:self.view.window];

- (void)windowWillClose:(NSNotification *)notification
    {
        NSWindow *win = [notification object];
        //...
    }

1
投票

您可以声明您的自定义类以符合

NSWindowDelegate
协议。

将自定义类的实例设置为窗口的委托

然后使用其中一种方法(可能是 windowWillClose: 之一)在窗口关闭之前执行某些操作。

- (BOOL)windowShouldClose:(id)sender
- (void)windowWillClose:(NSNotification *)notification

0
投票

您可以在每个 NSViewController 中执行以下操作 返回 true 将关闭窗口,返回 false 将不关闭它。

class ViewController: NSViewController, NSWindowDelegate {
    
    var firstWindow:NSWindow?
    override func viewDidLoad() {
        super.viewDidLoad()
        firstWindow = NSApplication.shared.windows.first
        firstWindow?.delegate = self
    }
        
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        // Do something appropriate here

        print("Window Should Close")
        return false
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.