在Swift中处理窗口的关闭事件 [英] Handle close event of the window in Swift
问题描述
如何使用swift处理窗口的关闭事件,例如,询问确定要关闭表单吗?"
How to handle close event of the window using swift, for example, to ask "Are you sure you want to close the form?"
在是"情况下将关闭该表单,而在否"情况下将不关闭该表单.显示消息框对我来说不是问题.
The form will be closed in the case "yes" and not closed in the case "no". Showing message box is not a problem for me.
viewWillDisappear()也可用于最小化,但我只需要关闭事件即可.
viewWillDisappear() works for minimizing also, but I need only close event.
谢谢.
推荐答案
就像上面说的,您应该将ViewController
设为NSWindowDelegate
,但是应该处理windowWillClose
,而不是windowShouldClose
. windowShouldClose
是确定窗口是否能够关闭,而不是窗口实际上正在关闭的事件.
Like said above, you should make the ViewController
an NSWindowDelegate
, but you should handle windowWillClose
, not windowShouldClose
. windowShouldClose
is to determine if the window is able to close or not, not an event that the window is actually closing.
我还发现您需要在viewDidAppear
中而不是viewDidLoad
中设置delegate
.对我来说self.view.window
在viewDidLoad
中尚未定义.
I also found that you need to set up the delegate
in viewDidAppear
, not viewDidLoad
. For me self.view.window
wasn't defined yet in viewDidLoad
.
override func viewDidAppear() {
self.view.window?.delegate = self
}
这篇关于在Swift中处理窗口的关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!