未调用 windowWillClose 和按钮操作 Swift

windowWillClose and button action not called Swift

我正在使用 Xcode 10(测试版)设计一个 mac 应用程序,我遇到了首选项 Window 控制器

的问题

我的 Main.storyboard 中有一个 NSWindowController 自定义 class PreferenceWindow带有工具栏的控制器。这是它的连接:

这里是完整的 class :

class PreferenceWindowController: NSWindowController, NSWindowDelegate {

@IBAction func didClickAuthor(_ sender: Any) {
    print("author")
}

@IBAction func didClickTypo(_ sender: Any) {
    print("typo")
}

override func windowDidLoad() {
    super.windowDidLoad()
}

func windowWillClose(_ notification: Notification) {
    print("willClose")
}
}

window 通过 AppDelegate class 使用此代码启动:

let storyboard = NSStoryboard(name: "Main",bundle: nil)

    if let wc = storyboard.instantiateController(withIdentifier: "PreferenceWindowController") as? PreferenceWindowController
    {
        wc.showWindow(self)
    }

window 按预期打开,工具栏可单击,但根本没有调用 PreferenceWindowController 中的任何功能,既没有关闭 window,也没有点击在工具栏上。

我检查了每个连接,每个 class 名称,我真的不知道出了什么问题...

解决方案

解决方案是将 PreferenceViewController class 作为变量存储在 AppDelegate class 中。

我的解决方案:

var preferenceWindowController:PreferenceWindowController? = nil

@IBAction func clickPreferences(_ sender: Any) {
    if let wc = storyboard.instantiateController(withIdentifier: "PreferencesWindowController") as? PreferenceWindowController {
        let window = wc.window
        preferenceWindowController = wc

        wc.showWindow(self)
    }
}

感谢您的帮助!

上面的评论似乎是对的。根据您在问题中包含的代码上下文,您创建的 window 控制器似乎只有该函数调用的生命周期。

尝试使 window 控制器成为实例变量。这通常是我在创建 window 控制器的 App 委托中进行连接的方式。这是一个效果很好的简单模式。