windowShouldClose(_ :)从未调用过

时间:2017-07-03 10:43:05

标签: swift3 xcode8 osx-elcapitan

我想在倒计时运行时阻止用户关闭主窗口(并退出应用程序)。 我已阅读有关该帖子的帖子,但遗憾的是,所解释的方法都不起作用。 我认为我做对了,但是windowShouldClose从不被调用,与其他两个函数不同。我很绝望。 :) 这是我在NSWindowController中的代码:

import Cocoa

class WindowController: NSWindowController, NSWindowDelegate {

override func windowDidLoad() {
    super.windowDidLoad()
    print("Window did load")
    self.window?.delegate = self
}

func windowShouldClose(sender: NSWindow) -> Bool {
    print("Window should close")
    let alert = NSAlert.init()
    alert.addButton(withTitle: "No")
    alert.addButton(withTitle: "Yes")
    alert.informativeText = "Close the window?"
    let response = alert.runModal()
    if response == NSAlertFirstButtonReturn {
        return true
    } else {
        return false
    }
}

func windowWillClose(_ notification: Notification) {
    print("Window will close")
}

func windowDidChangeScreen(_ notification: Notification) {
    print("Window did change screen")
}

}

2 个答案:

答案 0 :(得分:1)

永远不会调用

<SeekBar android:id="@+id/brushSize" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="84dp" android:layout_marginStart="84dp" android:layout_marginTop="24dp" android:max="100" android:progress="10" /> ,因为您将其声明为windowShouldClose(_:)

在Swift 3中,delegate method的签名是

windowShouldClose(:)

答案 1 :(得分:0)

我为Swift5 / Xcode 10支付2美分。

如果:  -您正在使用NSViewController(如iOS中的...。)  -您想在NSViewController派生类中使用逻辑(而不是在NSWindowController中)

是“ windowDidLoad”或“ awakeFromNib”中的无用设置委托。 (我在一个多平台的iOS / OS项目中需要它)

如此:

class ViewController: NSViewController, **NSWindowDelegate** {

您必须在viewWillAppear中设置它。

override func viewWillAppear() {
        // we choose to delegate ourselves
        let window = self.view.window
        window!.delegate = self
    }

(即使它从后台恢复也可以被调用。..

注意:

a)在某些情况下似乎是一种更好的方法来完全删除关闭按钮:

window!.styleMask.remove(.closable)

b)Apple Review不允许删除“关闭”按钮(但是可能会有用)