我需要知道用户何时完成对 NSTableView 中的单元格的编辑。该表包含所有用户的日历(从 CalCalendarStore 获得),因此为了保存用户的更改,我需要将更改通知 CalCalendarStore。但是,我找不到在用户完成编辑后调用的任何内容 - 我猜想在表的委托中会有一个方法,但我只看到在编辑开始时调用的方法,而不是在编辑结束时调用的方法。
6 回答
NSTableView
通过使用NSNotificationCenter
或使用方法,您可以在不进行子类化的情况下获得相同的结果NSControl
。请参阅此处的 Apple 文档:
http://developer.apple.com/library/mac/#qa/qa1551/_index.html
它只有几行代码,对我来说非常有效。
如果你可以成为delegate
你NSTableView
只需要实现该方法
- (void)controlTextDidEndEditing:(NSNotification *)obj { ... }
实际上,NSTableView
是它所包含delegate
的NSControl
元素的,并将那些方法调用转发给它delegate
(还有其他有用的方法)
否则,使用NSNotificationCenter
:
// where you instantiate the table view
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingDidEnd:)
name:NSControlTextDidEndEditingNotification object:nil];
// somewhere else in the .m file
- (void)editingDidEnd:(NSNotification *)notification { ... }
// remove the observer in the dealloc
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSControlTextDidEndEditingNotification object:nil];
[super dealloc]
}
使用 addObserver:toObjectsAtIndexes:forKeyPath:options:context 为内容数组中的每个项目设置观察者:
您还需要为数组本身设置一个观察者,以便您收到有关添加到数组中或从数组中删除的对象的通知。
以iSpend项目为例。
子类 NSTableView 并覆盖 textDidEndEditing: (一定要调用 super 的实现)。
这只会由文本字段 NSTextFieldCell 或 NSComboBoxCell 调用(但仅在通过键入来更改值时,而不是通过从组合菜单中选择值)。
查看 NSTableDataSource 协议。您正在查找的消息称为:tableView:setObjectValue:forTableColumn:row:
将@Milly 的答案翻译成Swift 3:
// Setup editing completion notifications
NotificationCenter.default.addObserver(self, selector: #selector(editingDidEnd(_:)), name: NSNotification.Name.NSControlTextDidEndEditing, object: nil)
处理通知的函数:
func editingDidEnd(_ obj: Notification) {
guard let newName = (obj.object as? NSTextField)?.stringValue else {
return
}
// post editing logic goes here
}
子类 NSArrayController 并覆盖 objectDidEndEditing: (一定要调用 super 的实现)。
这将主要仅由文本字段 NSTextFieldCell 或 NSComboBoxCell 调用(但仅在通过键入来更改值时,而不是通过从组合菜单中选择值)。可能还有一些其他的单元格会调用它,但我不确定哪些单元格。如果您有自定义单元格,请考虑实施 NSEditor 和 NSEditorRegistration 非正式协议。