3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:macOSメニューバーの項目の選択可否を動的に変更する

Posted at
AppDelegate.swift
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    
    @IBOutlet weak var menu: NSMenu! // Storyboardのメニューバーと接続しておく
    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    var isSelectable: Bool = true
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        statusItem.menu = menu

        let selectItem menu.item(withTag: 0) // 指定タグの項目と接続してみた
        selectItem?.target = self
        selectItem?.action = #selector(AppDelegate.select(_:))

        let quitItem menu.item(withTag: 1)
        quitItem?.target = self
        quitItem?.action = #selector(AppDelegate.quit(_:))
    }

    @objc func select(_ sender: NSMenuItem) {
        // do something
    }

    @objc func quit(_ sender: Any) {
        NSApp.terminate(self)
    }

}

extension AppDelegate: NSMenuItemValidation {
    
    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
        if menuItem.action == #selector(select(_:)) {
            return isSelectable // このフラグに基づき項目の選択可否が決まる
        }
    }

}

NSMenuItemValidationvalidateMenuItemを使ってNSMenuItemの選択可否を動的に管理することができる.

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?