简体   繁体   English

如何将 NSMenuItem(启用)的状态绑定到 NSNumber 的特定值?

[英]How do I bind a state of a NSMenuItem (enabled) to a specific value of an NSNumber?

How do I bind a state of a NSMenuItem (enabled) to a specific value of an NSNumber ?如何将 NSMenuItem(启用)的状态绑定到 NSNumber 的特定值?

ie IE

if myNumber ==2 then my NSMenuItem should be enabled如果 myNumber ==2 那么我的 NSMenuItem 应该被启用

I need to do this for several NSMenuItem:我需要为几个 NSMenuItem 执行此操作:

ie IE

if myNumber = 3 then my second NSMenuItem should be enabled如果 myNumber = 3 那么我的第二个 NSMenuItem 应该被启用

thanks谢谢

If you want to use a transformer, I think you'd have to write it yourself, as in this example .如果你想使用变压器,我认为你必须自己编写,如本例所示 It will register a class which defines a value transformer, which the system will then instantiate.它将注册一个定义值转换器的,然后系统将实例化它。

In case you want to register an instance as a value transformer, this doc has the details.如果您想将实例注册为值转换器, 此文档有详细信息。 The advantage if this will be that you can configure each instance differently without having to define a class for each situation.这样做的好处是您可以不同地配置每个实例,而不必为每种情况定义一个类。

I found ValueTransformer s to be too cumbersome for this.我发现ValueTransformer太麻烦了。 It gets much simpler than that.它变得比这简单得多。 Just create a controller object like below只需创建一个如下所示的控制器对象

class FooMenuController: NSObject {

    @IBAction func selectedNumberChanged(sender: NSMenuItem) {
        UserDefaults.fooNumber = sender.tag
    }
}

extension FooMenuController: NSMenuItemValidation {

    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
        let on = (menuItem.tag == UserDefaults.fooNumber)
        menuItem.state = on ? .on : .off
        return true
    }
}

In your MainMenu.xib drag out an NSObject instance from the library and set it to your FooMenuController subclass.在您的MainMenu.xib ,从库中拖出一个NSObject实例并将其设置为您的FooMenuController子类。 Now set the action on every NSMenuItem to FooMenuController.selectedNumberChanged and its tag value to the number it should represent.现在将每个NSMenuItem上的action设置为FooMenuController.selectedNumberChanged并将其tag值设置为它应该表示的数字。

Voila.瞧。

Use IBOutlet to your NSButton and disable all the button from interface builder.IBOutlet用于您的NSButton并禁用界面构建器中的所有按钮。 then use If else condition and enable your button.然后使用 If else 条件并启用您的按钮。

IBOutlet NSButton *my1;// Disable  
IBOutlet NSButton *my2; //Disable   
If(myNumber ==1)
 [my1 setState:NSOnState];
else If(myNumber ==2)
 [my1 setState:NSOnState];

您可以在 IB 中绑定它的(NSButton)“值”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM