【问题标题】:Prevent NSPopUpButton to open its menu阻止 NSPopUpButton 打开其菜单
【发布时间】:2017-11-18 15:26:08
【问题描述】:

我需要防止弹出的菜单在满足某些条件时被打开,所以我实现了“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??
    }
}

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

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

【问题讨论】:

  • 禁用按钮?但是你不会在 in 这个方法中这样做;你会在这个方法有机会被调用之前这样做。保持按钮禁用,直到“满足条件”。了解验证、绑定等。
  • mmh,我需要下次启用按钮(并再次检查),也是为了它的外观。禁用按钮时会发生这种情况吗?
  • 编辑了之前的评论。此弹出窗口位于大纲视图内(它是一个 plist 编辑器)。正如我所说的那样,使按钮被禁用会很糟糕。
  • 当弹出按钮没有弹出时用户会怎么想?如果控件不起作用,它应该是可见的。至少显示一个包含当前值的菜单。
  • @Willeke,是的,这是我想要避免的一个很好的理由。可能是我不够清楚。假设您在编辑“值”列但当前值是错误的“日期字符串”时单击 Xcode 的 plist 编辑器的“类型”列...编辑器询问是否要“继续编辑” ”。如果发生这种情况是因为您在“值”字段之外单击。问题是,如果您也单击弹出按钮(键入列),则会显示警报......而且弹出按钮的菜单......在警报顶部。我想避免的,但我没有说它应该不可见。

标签: swift nsmenu nspopupbutton


【解决方案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 是一个获取/设置变量。 “错误值”是这样工作的:

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() 是关键!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多