Bind to negation of Boolean property with KVO

I use KVO to view the checkbox and to enable or disable the details input area based on the status of the checkbox. (Ie, if the box is checked, the details pane is activated, otherwise) Something like:

[self.detailInputArea bind:@"enabled" toObject:self withKeyPath:@"enabledCheckbox" options:nil]; 

My problem is that now I would like to change this to set the detailInputArea hidden property detailInputArea to show / hide the view depending on the state of the checkbox. The problem is that this will require reverse logic. In other words, if you set it to enabled, true means that the view is turned on (can accept input), and false means that it cannot. However, with hidden, true means that the view is hidden, and false otherwise. Obviously, this will not work, since the view will hide when the checkbox is checked (its enabled property is true).

Is there any way to change this binding in order to act based on the inverse property they observe and / or is there a better way to accomplish what I'm trying to do here?

+7
cocoa cocoa-bindings key-value-observing
source share
2 answers

Yes, this is part of what a parameter dictionary is for. Key binding allows you to convert the bound value before setting it through NSValueTransformer , and you can specify the transformer in the binding parameters.

The NSValueTransformer class provides named transformers by default . In this case, you will be interested in NSNegateBooleanTransformerName .

So the binding you want will look like this:

 [self.detailInputArea bind:@"hidden" toObject:self withKeyPath:@"enabledCheckbox" options:@{NSValueTransformerNameBindingOption : NSNegateBooleanTransformerName}]; 
+12
source share

Here is Josh Caswell's Answer in Swift 3 :

 detailInputArea.bind(NSHiddenBinding, to: self, withKeyPath: #keyPath(enabledCheckbox), options: [NSValueTransformerNameBindingOption: NSValueTransformerName.negateBooleanTransformerName]) 
+1
source share

All Articles