Reputation: 367
I'm using Cocoa and Swift 3 to develop for MacOS. I am trying to use the following code to set a user defaults key (boolean) to true
when a user clicks on a menu item, on the main menu.
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
}
}
The app does perform the segue, but none of the functions. I assume it is because it performs the segue first therefore bypassing my code, that makes the most sense to me. I would like to set the key to true
and have a segue out of the main menu (File>Connection Handler
) when this menu item is clicked. Hopefully that makes sense, thanks in advance.
Upvotes: 1
Views: 142
Reputation: 17060
Instead of an IBAction, you can synchronize your menu item to a Boolean value in your user defaults simply by dragging a User Defaults Controller into the scene containing your menu bar, and then binding the "Value" binding of your menu item to the user defaults controller, with your defaults key in the "Model Key Path" field. I just tried this, and it seems to keep the value synced even when the menu item is also set to perform a segue.
Upvotes: 1