如何使用Swift处理窗口的关闭事件,例如,询问“您确定要关闭表格吗?”?
就像上面所说的,你应该将ViewController
设置为NSWindowDelegate
,但是你应该处理windowWillClose
而不是windowShouldClose
。 windowShouldClose
用于确定窗口是否能够关闭,而不是窗口实际关闭时发生的事件。
我还发现你需要在viewDidAppear
中设置delegate
,而不是在viewDidLoad
中。因为在viewDidLoad
中,self.view.window
还未定义。
override func viewDidAppear() {
self.view.window?.delegate = self
}
我也有同样的疑问,但在这里详细解释的方法中解决了它:Quit Cocoa App when Window Close using XCode Swift 3
需要三个步骤:
添加的代码应该像这样:
class ViewController: NSViewController, NSWindowDelegate {
// ... rest of the code goes here
override func viewDidAppear() {
self.view.window?.delegate = self
}
func windowShouldClose(_ sender: Any) {
NSApplication.shared().terminate(self)
}
}
class ViewController: NSObject, NSWindowDelegate
windowShouldClose:
。在此方法中,您可以使用NSAlert提示用户是否真的想要关闭窗口。 编辑(响应@Mr Beardsley的评论)告诉代理用户已尝试关闭窗口[...]
window.delegate = self
当self
是视图控制器,window
是正在使用的窗口时。您可以将此代码放在viewDidLoad:
中。
func applicationShouldTerminateAfterLastWindowClosed (_ theApplication: NSApplication) -> Bool {
return true
}