带segue的MacOS应用程序类数据

时间:2017-08-20 19:54:41

标签: swift cocoa segue nsuserdefaults nsapplication

我正在使用Cocoa和Swift 3为MacOS开发。我试图使用以下代码在用户点击主菜单上的菜单项时将用户默认密钥(布尔值)设置为true

class app: NSApplication, NSApplicationDelegate {
@IBOutlet weak var connec: NSMenuItem! 
@IBAction func connec(_ sender: Any) { //User has clicked the menu item
    UserDefaults.standard.set(true, forKey: "CalledFromMenu")
    UserDefaults.standard.synchronize() //I know it's deprecated, worth a shot though
    print(UserDefaults.standard.value(forKey: "CalledFromMenu"))
    print("menu")
    //Neither of these actually print when I click the button, but the segue happens.
   //There is a Show segue in the interface builder, I cannot invoke a custom SegueWithIdent here either
   }
}

应用确实执行了segue,但没有执行任何功能。我认为这是因为它首先执行segue,因此绕过我的代码,这对我来说是最有意义的。我想将密钥设置为true,并在单击此菜单项时从主菜单(File>Connection Handler)中删除一个segue。希望这是有道理的,提前谢谢。

1 个答案:

答案 0 :(得分:0)

您只需将用户默认控制器拖动到包含菜单栏的场景中,然后将菜单项的“值”绑定绑定到用户默认值,即可将菜单项同步到用户默认值中的布尔值,而不是IBAction。用户默认控制器,在“模型密钥路径”字段中使用默认密钥。我只是尝试了这个,它似乎保持值同步,即使菜单项也设置为执行segue。