我创建了一个带有单列的基于 View NSTableView
。此列使用 Interface Builder 中的标准 NSTableCellView
进行填充(我选择了带有图像和文本字段的版本)。
现在我想让列中的文本字段可编辑。
我的第一次尝试是从界面构建器修改 NSTextField
并将其行为设置为可编辑
。它确实有效,当我选择一行并按下回车键
时,该字段变为可编辑状态,并且我可以更改其值。我认为我能够拦截此更改,这要归功于一些 NSTableViewDataSource
方法,例如 tableView:setObjectValue:forTableColumn:row:
但永远不会调用此方法来响应文本字段编辑行动。
在基于 View 的 NSTableView 系统中处理可编辑字段的正确方法是什么?我认为 NSTableViewDataSource
与它有关,但我不知道如何调用它的方法。
最佳答案
创建 NSTableCellView 的子类。 (适当的 .h 和 .m 文件)使类响应 NSTextFieldDelegate 协议(protocol)。实现control:textShouldEndEditing:方法。使该子类成为标签控件的委托(delegate)。
这是一些示例代码。
CategoryListCell.h
@interface CategoryListCell : NSTableCellView
@end
CategoryListCell.m
@interface CategoryListCell()<NSTextFieldDelegate>
@property (weak) IBOutlet NSTextField *categoryLabel;
@property (assign) BOOL editing;
@property (copy) NSString* category;
@end
@implementation CategoryListCell
- (BOOL)control:(NSControl*)control textShouldBeginEditing:(NSText *)fieldEditor {
self.editing = YES;
return YES;
}
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor; {
if (self.editing) {
self.editing = NO;
[self mergeFromSource:self.category toDestination:self.categoryLabel.stringValue];
}
return YES;
}
- (void)mergeFromSource:(NSString*)source toDestination:(NSString*) destination {
// your work here
}
@end
关于macos - 使 NSTableCellView 可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13745025/