Storyboardでメニューのオンオフの仕方の一例を紹介したいと思います。
AppDelegateの中にvalidateMenuItemメソッドを作成します。
有効にしたい条件の時にtrueを返し、それ以外の無効にしたい場合はfalseを返します。
またどのメニュー項目かはここではmenuItem.Titleで判別しています。
因みにViewControllerの中でvalidateMenuItemを作成してもうまく行きませんでした。
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//ViewControllerを保持
//メニューのオンオフに関係する変数を持っているので参照できるように変数で持っておく。
//ViewControllerの中で設定しています。
var mainView: ViewController? = nil
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.title {
case "CSV読み込み":
return true
case "CSV保存":
if mainView != nil && mainView!.blOpenedCSV == true {
return true
} else {
return false
}
case "行をコピー":
if mainView != nil {
if mainView!.blOpenedCSV == true && mainView!.tv.selectedRow > -1 {
return true
} else {
return false
}
} else {
return false
}
default:
return true
}
}
@IBAction func doReadCSV(_ sender: Any) {
if mainView != nil {
mainView!.readCSV(self)
}
}
@IBAction func doSaveCSV(_ sender: Any) {
if mainView != nil {
mainView!.saveCSV(self)
}
}
}
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
//アプリケーションの変数
var myApp = NSApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//AppDelegateの変数に自身のインスタンスを保存することによって、
//AppDelegateでのメニューのオンオフをする為の助けにします。
myApp.mainView = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
