In Interface Builder
Making the transition in Interface Builder is pretty easy. Simply select the NSTableView
, go to the Attributes Inspector, then change the Content Mode from Cell Based to View Based. This will add NSTableCellViews to your existing columns.
You’ll want to copy the NSTableViewColumn’s identifier (under the Identity Inspector) to the new NSTableCellView’s identifier. You’ll also want to change the new NSTextFieldCells to match the attributes of your old ones.
NSTableViewDelegate
: cell values
You will want to replace your instances of - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
with - (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
. In theviewForTableColumn
method, you’ll use - (id)makeViewWithIdentifier:(NSString *)identifier owner:(id)owner
to grab an instance of the view you need, and from there you can customize it. It’ll look something like this:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
NSTableCellView *tableCellView = [tableView makeViewWithIdentifier:[tableColumn identifier] owner:self];
if ([[tableColumn identifier] isEqualToString:@"identifier"]) {
[[tableCellView textField] setObjectValue:@"object"];
}
}
NSTableViewDelegate
: customizing cells
In Iron Money for Mac, the amount column displays positive amounts in green and negative amounts in red. - (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
is not used in view-based NSTableViews, so you’ll want to customize the instances of NSTableCellView
used in columns for which you’d like to customize their display.
First, create a new subclass of NSTableCellView
. In this subclass, you can implement whatever methods you need to customize the display of your view (or the text field inside your view). In the case of Iron Money for Mac, that meant implementing - (void)setBackgroundStyle:(NSBackgroundStyle)style
and changing the text field cell’s text color. Here’s an example of what it would look like if you wanted the column’s text to appear in red while it wasn’t selected:
@implementation CustomTableCellView
-(void)setBackgroundStyle:(NSBackgroundStyle)style {
if (style == NSBackgroundStyleDark) {
[self.textField.cell setTextColor:[NSColor selectedTextColor]];
} else {
[self.textField.cell setTextColor:[NSColor redColor]];
}
[super setBackgroundStyle:style];
}
@end
Then, in Interface Builder, you’ll select the appropriate NSTableCellViews and change their Class (under the Identity Inspector) to an instance of your new NSTableCellView
subclass.