2015-10-19 116 views
3

如何使用swift处理窗口的关闭事件,例如,询问“您确定要关闭表单吗?”在Swift中处理窗口的关闭事件

enter image description here

的形式将的情况下被关闭“是”而不是“不再”封闭。显示消息框对我来说不是问题。

viewWillDisappear()也适用于最小化,但我只需要关闭事件。

谢谢。

回答

3

您可以在您的ViewController类中使用NSWindowDelegate协议。 (见documentation here

要使类符合协议:

class ViewController: NSObject, NSWindowDelegate 

为了检测窗口的关闭按钮被点击时,使用windowShouldClose:

从DOC:

告知代表用户试图关闭窗口[...]

在这种方法中,您可以使用NSAlert来提示用户是否真的要关闭窗口。

编辑(响应@Mr比尔兹利的评论)

为了让您的ViewController委托,使用:

window.delegate = self 

哪里self是视图控制器和window是您正在使用的窗口。你可以把这个放在viewDidLoad:

+0

感谢您的回答。我设置了“类ViewController:NSObject,NSWindowDelegate”并实现了函数windowShouldClose。但它不起作用。我相信我应该为窗口设置委托属性,但我不知道如何。 – Evgeniy

+2

要设置从您的视图控制器委托只是做一些事情:“window.delegate = self”在viewDidLoad(只要你在10.10或更高版本)。您还需要一个参考或IBOutlet到相关窗口。 –

9

就像上面说的那样,你应该使ViewControllerNSWindowDelegate,但是你应该处理windowWillClose而不是windowShouldClosewindowShouldClose用于确定窗口是否能够关闭,而不是窗口实际关闭的事件。

我还发现您需要在viewDidAppear中设置delegate,而不是viewDidLoad。对于我self.view.window尚未在viewDidLoad中定义。

override func viewDidAppear() { 
    self.view.window?.delegate = self 
} 
+0

self.view.window?.delegate = self do plz? –

+0

将ViewController设置为ViewController表示的Window的委托。它允许符合NSWindowDelegate协议的ViewController实际上充当代理。 –

+2

Thx。使用viewDidAppear为我工作。 – VaporwareWolf

4

我有同样的查询也解决了它使用的方法在这里详细解释说:Quit Cocoa App when Window Close using XCode Swift 3

它需要三个步骤:

  1. 顺应toNSWindowDelegate在你的ViewController类
  2. 覆盖viewDidAppear方法
  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) 
    } 
} 
+1

windowShouldClose是一个委托方法,它返回一个布尔值以确定是否允许窗口关闭。你应该使用windowWillClose。您也不需要在代码中手动终止应用程序。有一个NSApplicationDelegate方法可以放在AppDelegate中,以便在所有窗口关闭时关闭应用程序。 func applicationShouldTerminateAfterLastWindowClosed(_ sender:NSApplication) - > Bool { return true } –