Search code examples
objective-ccocoanstableviewnsbutton

Enable a button based on a value in the NSTableview


I have a NSTableview. I need to enable the button based on a value of a column in the tableview. For instance, In the table view i have a column, Status. I have 2 kinds of status, Withdrawn and Booked. If i click on a row which has the status as Withdrawn, i need to disable the withdraw button. Can i be able to do it through binding? How could i do it? Pls help me out. Thanks.


Solution

  • Provided you create a custom NSValueTransformer, you can enable or disable the button using bindings.

    You can bind the Enabled property of the button as follows:

    Bind to: arrayController

    Controller Key: selection

    Model Key Path: status

    Value Transformer: MDStatusValueTransformer

    NOTE: in place of arrayController, you should select whatever the name of your array controller is in the nib file. In place of MDStatusValueTransformer, you should specify whatever class name you end up naming the class I've provided below.

    As I mentioned, you'll need to create a custom NSValueTransformer. The enabled property expects a BOOL wrapped in an NSNumber, but your status property is an NSString. So, you'll create a custom NSValueTransformer that will examine the incoming status NSString, and return NO if status is equal to @"Withdrawn".

    The custom NSValueTransformer should look something like this:

    MDStatusValueTransformer.h:

    @interface MDStatusValueTransformer : NSValueTransformer
    
    @end
    

    MDStatusValueTransformer.m:

    @implementation MDStatusValueTransformer
    
    + (Class)transformedValueClass {
        return [NSNumber class];
    }
    
    + (BOOL)allowsReverseTransformation {
        return NO;
    }
    
    - (id)transformedValue:(id)value {
        if (value == nil) return nil;
        if (![value isKindOfClass:[NSString class]]) return nil;
    
        if ([value isEqualToString:@"Withdrawn"]) {
             return [NSNumber numberWithBool:NO];
        }
        return [NSNumber numberWithBool:YES];
    }
    
    @end