Adding an editable NSTextFieldCell to my NSTableView

妖精的绣舞 提交于 2019-12-07 19:23:27

问题


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!)



来源:https://stackoverflow.com/questions/6026393/adding-an-editable-nstextfieldcell-to-my-nstableview

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