Handle close event of the window in Swift

萝らか妹 提交于 2019-12-07 03:10:07

问题


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() works for minimizing also, but I need only close event.

Thanks.


回答1:


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.

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
}



回答2:


I was having the same query too, solved it using the method explained in detail here: Quit Cocoa App when Window Close using XCode Swift 3

It needs three steps:

  1. Conform toNSWindowDelegate in your ViewController class
  2. Override viewDidAppear method
  3. Add windowShouldClose method

The added code should look like this:

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)
    }
}



回答3:


You can use the NSWindowDelegate protocol in your ViewController class. (See the documentation here)

To make your class conform to the protocol:

class ViewController: NSObject, NSWindowDelegate

To detect when the window's close button has been clicked, use windowShouldClose:

From the doc:

Tells the delegate that the user has attempted to close a window [...]

In this method, you can use NSAlert to prompt the user on whether or not they really want to close the window.

EDIT (in response to @Mr Beardsley's comment)

To make your ViewController the delegate, use:

window.delegate = self

Where self is the ViewController and window is the window you're using. You can put this in viewDidLoad:.



来源:https://stackoverflow.com/questions/33215860/handle-close-event-of-the-window-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!