macos - 使 NSTableCellView 可编辑

标签 macos cocoa nstableview

我创建了一个带有单列的基于 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/

相关文章:

objective-c - 显示带有许多可点击 URL 的文本

macos - View 支持的 NSTableView : Inserted Column Width/Margin Issues

macos - 以编程方式更改屏幕保护程序设置

swift - 如何在 macOS 的 SwiftUI 中使用菜单命令实现多窗口?

java - 在 Mac 中解码使用 base64 编码的文件

ios - 如果您要查看 nib 文件的内部,它究竟是什么样子的?

xcode - 使用 Storyboard更改 NSWindow 大小

objective-c - NSTableView 圆角像 UITableView Groups

macos - KVO : not receiving notifications on NSTableView's -selectedRowIndexes?

macos - 初始化 OS X 应用程序 UI 的代码最好放在哪里?