尝试知道基于macOS Document的应用程序中的窗口何时关闭 [英] Trying to know when a window closes in a macOS Document based application

查看:95
本文介绍了尝试知道基于macOS Document的应用程序中的窗口何时关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图知道何时关闭窗口,我实现了以下代码:

  class ViewController:NSViewController,NSWindowDelegate { 

覆盖func viewDidLoad(){
super.viewDidLoad()

让窗口:NSWindow吗? = view.window
window?.delegate = self
}

func windowWillClose(_ aNotification:Notification){
print( windowWillClose)
}

}

不幸的是什么都没有发生,我怎么可能做错了? / p>

文档: https: //developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification



PS
我已经读过这个问题,没有找到解决方案:在Swift中处理窗口的关闭事件

解决方案

问题在于window属性将始终在viewDidLoadMethod内部返回nil。您需要在viewWillAppear方法内设置委托:

  class ViewController:NSViewController,NSWindowDelegate {
覆盖func viewWillAppear() {
super.viewWillAppear()
view.window?.delegate = self
}
func windowWillClose(_ aNotification:Notification){
print( windowWillClose)
}
}


I'm trying to know when a window closes, I implemented this code:

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let window: NSWindow? = view.window
        window?.delegate = self
    }

    func windowWillClose(_ aNotification: Notification) {
        print("windowWillClose")
    }

}

Unfortunately nothing happens, what could I made wrong?

Documents: https://developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification

PS I already read this question without to find a solution: Handle close event of the window in Swift

解决方案

The problem there is that the window property will always return nil inside viewDidLoadMethod. You need to set the delegate inside viewWillAppear method:

class ViewController: NSViewController, NSWindowDelegate {
    override func viewWillAppear() {
        super.viewWillAppear()
        view.window?.delegate = self
    }
    func windowWillClose(_ aNotification: Notification) {
        print("windowWillClose")
    }
}

这篇关于尝试知道基于macOS Document的应用程序中的窗口何时关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆