试图了解基于macOS Document的应用程序窗口何时关闭

时间:2017-06-21 20:11:12

标签: swift cocoa

我想知道窗口何时关闭,我实现了这段代码:

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

}

不幸的是没有任何事情发生,我有什么不对的?

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

PS 我已经在没有找到解决方案的情况下阅读了这个问题:Handle close event of the window in Swift

1 个答案:

答案 0 :(得分:3)

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

<div style="text-align:center;"><a href="http://www.coolfundraisingideas.net/" alt="Fundraising Thermometer"><img id="thermometer" border="0" src="http://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=100&current=25&color=red&size=large"></a>
    <p style="font-size:.8em; color:#999">Provided by <a href="http://www.coolfundraisingideas.net/" rel="nofollow" style="display:block; text-decoration:none; font-size:.8em; color:#999">CoolFundraisingIdeas.net</a></p>
</div>
<script>
    function therData() {
        var current = arguments[0].query.results.body.root.eventfundraisingtotals_collection.eventfundraisingtotals.eventverifiedtotalcollected;
        var goal = arguments[0].query.results.body.root.eventfundraisingtotals_collection.eventfundraisingtotals.eventverifiedfundraisinggoal;
        document.getElementById('thermometer').src = 'http://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=' + goal + '&current=' + current + '&color=red&size=large';
        document.getElementsByTagName('head')[0].removeChild(document.getElementById('therScript'));
    }
    var therScript = document.createElement('script');
    therScript.setAttribute('id', 'therScript');
    therScript.src =
        "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D'http%3A%2F%2Fmy.e2rm.com%2Fwebgetservice%2Fget.asmx%2FgetEventFundraisingTotals%3FeventID%3D223256%26loginOrgID%3DASOSEW%26locationExportID%3D%26Source%3D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=therData";
    document.getElementsByTagName('head')[0].appendChild(therScript);
</script>