NSMenu 和 NSStatusItem 动作不能一起工作

NSMenu and NSStatusItem action wont work together

附加到 NSStatusItem 的按钮未向其目标选择器发送调用。

我不确定我到底做错了什么。我相信它与 button.action 行有关。

let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
let popover = NSPopover()

func applicationDidFinishLaunching(_ aNotification: Notification) {
    if let button = statusItem.button{
        button.image = NSImage(named:NSImage.Name("StatusBar"))
        button.action = #selector(someAction(_:)) //need help here

    }
    popover.contentViewController = QuotesViewController.freshController()
    constructMenu();

}

@objc func someAction(_ sender: Any?){
    print("working");
}

我正在学习本教程 - raywenderlich

编辑

这个设置操作的过程适用于我拥有的所有 NSMenuItems。我仍然是 NSStatusItem 的问题。

编辑 2

我认为显示的代码是正确的,我现在认为其他地方还有问题。

编辑 3 个答案

"If the status item has a menu set, the action is not sent to the target when the status item is clicked; instead, the click causes the menu to appear."- appledev NSStatusItem.action

"If the status item has a menu set, the action is not sent to the target when the status item is clicked; instead, the click causes the menu to appear."- apple dev NSStatusItem.action

您可以根据需要为按钮动态分配和显示菜单 属性。你需要实现 NSMenu menuDidClose 方法

self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength];
[self.statusItem.button sendActionOn: (NSLeftMouseUpMask|NSRightMouseUpMask)];
[self.statusItem.button setAction: @selector(statusItemClicked:)];

-(IBAction) statusItemClicked: (id) sender
{
    NSEvent *currentEvent = [NSApp currentEvent];

    // Right click conditions
    if  ((([currentEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask) ||
        (([currentEvent modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) ||
        (([currentEvent modifierFlags] & NSRightMouseUpMask) == NSRightMouseUpMask) ||    
        (([currentEvent modifierFlags] & NSRightMouseDownMask) == NSRightMouseDownMask) ||
        ([currentEvent type] == NSRightMouseDown) ||
        ([currentEvent type] == NSRightMouseUp))
    {
        [self showStatusMenu: self];
    }
    else
    {
        // do something besides showing the menu    
    }    
}

-(IBAction) showStatusMenu: (id) sender
{
    self.statusItem.menu = self.statusMenu;
    [self.statusItem.button performClick:nil];
}


-(void) menuDidClose : (NSMenu *) someMenu
{
    if (someMenu == self.statusMenu)
    {
            // re-configure statusitem
            self.statusItem.menu = nil;
            [self.statusItem.button sendActionOn: (NSLeftMouseUpMask|NSRightMouseUpMask)];
            [self.statusItem.button setAction: @selector(statusItemClicked:)];
    }
}