Reputation: 64854
This is how I enable/disable a NSMenuItem depending on the selection of items in a NSArrayController.
However I would like to disable the NSMenuItem in one more case: when the selection is multiple. In other terms, if more than one item is selected it should be disabled.
Thanks
Upvotes: 1
Views: 416
Reputation: 753
@bijan's transformedValue: method could be improved:
- (id)transformedValue:(id)value{
if(value == nil)
{
return @(NO);
}
if([value respondsToSelector:@selector(unsignedIntegerValue)] == NO)
{
return @(NO);
}
NSUInteger count = [value unsignedIntegerValue];
return @(count > 0);
}
Upvotes: 1
Reputation: 1685
You could subclass NSValueTransformer for this!
Implementation would look something like this:
@implementation CountToEnabledTransformer
+ (Class)transformedValueClass {
return [NSNumber class];
}
+ (BOOL)allowsReverseTransformation {
return NO;
}
- (id)transformedValue:(id)value{
int count = value;
BOOL boolValue = 0;
if ((count > 1) || (count == 0)) {
boolValue = 0;
}else {
boolValue = 1;
}
NSNumber *boolNumber = [NSNumber numberWithBool:boolValue];
return boolNumber;
}
@end
That takes in the @count
value, performs an if statement and returns an appropriate boolean value, to bind your enabled
property to.
Don't forget to register your newly created NSValueTransformer sublclass:
[NSValueTransformer setValueTransformer:[[CountToEnabledTransformer alloc] init] forName:@"CountToEnabledTransformer"];
A good place to do this is - (void)applicationDidFinishLaunching
, so it's already registered, when you nib tries to bind to it!
After that, just type in the NSValueTranformer's sublass name into the appropriate text field in the IB bindings inspector.
Upvotes: 0