Cocoa Bindings - NSTableView - Swapping Values

你说的曾经没有我的故事 提交于 2019-12-06 16:30:19

Yes, NSValueTransformer subclasses work just fine for this purpose.

You can also add read-only computed properties to your managed object class, and that should work, too. Those properties can even be added by a category in the controller code, if they don't make sense as part of the model code.

For example:

+ (NSSet*) keyPathsForValuesAffectingStatusDisplayName
{
    return [NSSet setWithObject:@"status"];
}
- (NSString*) statusDisplayName
{
    NSString* status = self.status;
    if ([status isEqualToString:@"0"])
        return @"Pending";
    else if ([status isEqualToString:@"1"])
        return @"Completed";
    // ...
}

The +keyPathsForValuesAffectingStatusDisplayName method lets KVO and bindings know that when status changes, so does this new statusDisplayName property. See the docs for +keyPathsForValuesAffectingValueForKey: to learn how that works.

I ended up using what at first appeared to be blocking the display of different info in those cells, using:

#pragma mark - Table View Delegate

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    /*  tableColumn = (string) @"AutomaticTableColumnIdentifier.0"
                row = (int)    0          */
    NSString *identifier = [tableColumn identifier];
    NSTableCellView *cellView = [tableView makeViewWithIdentifier:identifier owner:self];

    NSManagedObject *item = [self.itemArrayController.arrangedObjects objectAtIndex:row];

    if ([identifier isEqualToString:@"AutomaticTableColumnIdentifier.0"]) {
        /*  subviews returns array with  0 = Image View &
                                         1 = Text Field      */
        /*  First, set the correct timer image  */
        ...  logic  ...
        NSImageView *theImage = (NSImageView *)[[cellView subviews] objectAtIndex:0];
        theImage.image = [NSImage imageNamed:@"green.gif"];

        /*  Second, display the desired status  */
        NSTextField *theTextField = (NSTextField *)[[result subviews] objectAtIndex:1];
        ...  logic  ...
        theTextField.stringValue = @"Pending";
    }

    return cellView;
}

Apple's documentation states (somewhere) that bindings with an Array Controller can work in combination with manually populating the table view cells. It seems best and easiest to start with bindings and then refine display values manually.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!