Pergunta

I am using KVO to watch a checkbox, and to enable or disable a details input area based on the checkbox's state. (I.e. if the checkbox is checked, the details area is enabled, otherwise not) Something like:

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

My problem is that now I would like to change this to instead set detailInputArea's hidden property, to show/hide the view depending on the state of the checkbox. The problem is that this would require inverse logic. In other words, when setting its enabled, true means the view is enabled (can accept input) while false means it can't. However, with hidden, true means the view is hidden, and false otherwise. Obviously this wouldn't work, as the view would hide itself when the checkbox is checked (its enabled property is true).

Is there any way I can change this binding to act based on the inverse of the property it's watching, and/or is there a better way of accomplishing what I am trying to do here?

Foi útil?

Solução

Yes, this is part of what the options dictionary is for. Key-value binding allows the bound value to be transformed before it is set, via an NSValueTransformer, and you can specify the transformer in the options for the binding.

The NSValueTransformer class provides some default, named transformers. In this case, you'll be interested in NSNegateBooleanTransformerName.

Thus the binding you want will look like:

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

Outras dicas

Here's Josh Caswell's answer in Swift 3:

detailInputArea.bind(NSHiddenBinding,
                     to: self,
                     withKeyPath: #keyPath(enabledCheckbox),
                     options: [NSValueTransformerNameBindingOption: NSValueTransformerName.negateBooleanTransformerName])
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top