Reputation: 79
I have 3 view controllers say main1, main2 and child. I have added a menu item, on click of that it should open child view controller as modal. Whenever user is in main1 VC, menu item should be enabled. If user in main2 VC, menu should be disabled. Right now I’ve added modal segue between menu item and child VC. I followed following approaches to disable, but they are not working.
Method 1: In main2 VC, I’ve added
func validateUserInterfaceItem(_ anItem: NSValidatedUserInterfaceItem) -> Bool {
return false
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
return false
}
Method 2:
override func viewDidLoad() {
super.viewDidLoad()
let mainMenu = NSApplication.shared().mainMenu!
let appMenu = mainMenu.item(at: 0)!.submenu
appMenu?.item(withTitle: someMenuTitle)?.isEnabled = false
}
Upvotes: 3
Views: 779
Reputation: 5320
If you use a modal segue it will be always activated. To enable/disable dependent on the presented view controller I would add an action to the view controller to open the view controller manualy as modal. The menu item has to be connected to the action (openModalViewController) with the first responder.
@IBAction func openModalViewController(_ sender: AnyObject) {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateController(withIdentifier: "MyViewController") as! NSViewController
presentAsModalWindow(viewController)
}
Consider there must be at least one view able to get the first responder in main1/main2 that the menu item will activate. If this is not the case you would have to implement acceptsFirstResponder
for the corresponding view.
override var acceptsFirstResponder: Bool{
return true
}
To implement validateUserInterfaceItem
would be not required in this case, only if you want to control activation/deactivation dependent on an additional state as in the example below.
extension ViewController: NSMenuItemValidation {
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.action == #selector(delete(_:)) {
return tableView.selectedRow < 0 ? false : true
}
return true
}
}
Upvotes: 2