Adding an editable NSTextFieldCell to my NSTableVi

2019-05-23 07:03发布

问题:

I have an NSTableView which displays some information representing a custom object of mine. I am not using bindings.

Typically, I create my own NSCells to display data, but for once I'm after an NSTextFieldCell that will display a string value of the object, as well as let the user edit it.

I can successfully add the NSTextFieldCell using the code below, but it is not editable.

NSTextFieldCell *textField = [[NSTextFieldCell alloc] init];
[textField setFont:[NSFont fontWithName:@"Helvetica Bold" size:13]];
[textField setTextColor:[NSColor colorWithDeviceRed:0.1058823529 green:0.2117647059 blue:0.3294117647 alpha:1.0]];
[textField setStringValue:projectName];
[textField setEditable:YES];
[textField setBordered:NO];

[textField drawWithFrame:textRect inView:controlView];
[textField release];

Could someone please help me with this?

回答1:

NSTextFieldCell is implemented with the flyweight pattern (I read about it in the "Cocoa Design Patterns" book) and each column has only one instance of a cell. You can see some kind of evidence of this when you edit it in interface builder. When you click to edit an NSTableView, that single instance of the cell jumps in from where it was before and handles the editing for you.

As you say, doing this works for the visual appearance (drawing) of the cell, and works for NSTextField as well because each NSTextField must have just one cell per view, and therefore it's around when you want to edit it.

However in this case, you are creating a cell, drawing it, then kicking it out of memory by releasing it at the end of your code. So how do you expect this cell which you have set as editable to be around when you try to edit it? It doesn't exist anymore.

Try creating a single cell when the table view is set up and setting your custom cell to the right table column using this:

- (void)setDataCell:(NSCell *)aCell

Alternatively you could subclass NSTextFieldCell and do your customization there, and set the cell class for the column in interface builder (or XCode 4 if you're on the bleeding edge!)