阻止NSPopUpButton打开其菜单

时间:2017-11-18 15:26:08

标签: swift nsmenu nspopupbutton

我需要阻止在满足某些条件时打开弹出菜单,所以我实现了“willOpenMenu”来知道菜单即将打开的时间:

class MyPopUpButton: NSPopUpButton { 
    override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
        print("willOpenMenu")
        // it fires, but what I can do to prevent menu to be opened??
    }
}

现在,如何防止菜单显示?

EDIT 下面,按顺序,当您正在编辑“值”列时单击弹出窗口(类型列)时会发生什么 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

最后我找到了方法:

override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
    if (self.outline != nil) {
        /*
         the following is needed when user click on the type column:
         He can have ongoing edits on some rows, so changing first responder
         We can aesily inform the outline that We're playing with something else
         and have to force ask the user in case edits are wrong.
         This also prevent a crash.
         */
        if (self.outline?.wrongValue)! {
            // this grant the popup menu to not showup (or disappear so quickly)
            menu.cancelTrackingWithoutAnimation() 
        }
        self.window?.makeFirstResponder(self)
        self.window?.makeFirstResponder(self.outline)
    }
}

self.outline是一个get / set变量。 " wrongvalue"以这种方式工作:

override func controlTextDidBeginEditing(_ obj: Notification) {
    if obj.object is MyTextField {
        self.outline.wrongValue = true
    }
}

    override func controlTextDidEndEditing(_ obj: Notification) {
        if obj.object is MyTextField {
            /*
             some code here to check if stringValue is ok for the selected tag, otherwise
             show the relative alert, the popup menu will not show up anymore
             because cancelTracking is called on it
             */
            self.outline.wrongValue = false
        }
    }

cancelTracking()是关键!