要支持与Swift和ObjC不同的语言,我需要了解如何为NSTreeController
设置NSOutlineView
。
我已经能够在代码中创建NSOutlineView
,同时提供我自己的DataSource委托。但现在我想切换到使用NSTreeController
。我无法弄清楚如何设置绑定和其他关系,因为我可以找到的所有示例都假设使用Interface Builder进行设置。
答案 0 :(得分:0)
我想我现在已经找到了基础知识。为了记录,这是我必须添加到我已经管理了NSOutlineView的视图控制器,我自己管理数据源:
为树节点创建一个类:
@property (nonatomic, retain) NSTreeController *treeController;
@property (nonatomic, retain) NSMutableArray *treeContents;
将这些属性添加到视图控制器:
awakeFromNib
初始化树控制器,例如来自视图控制器的self.treeContents = [NSMutableArray array]; // holds the add nodes
self.treeController = [[NSTreeController alloc] init];
[self.treeController setLeafKeyPath:@"isLeaf"]; // refers to DataNode
[self.treeController setChildrenKeyPath:@"children"]; // refers to DataNode
// set up the bindings
[self.treeController bind:@"contentArray" toObject:self withKeyPath:@"treeContents" options:@{NSRaisesForNotApplicableKeysBindingOption:@YES, NSConditionallySetsEditableBindingOption:@YES}];
[self.table bind:@"content" toObject:self.treeController withKeyPath:@"arrangedObjects" options:@{NSAlwaysPresentsApplicationModalAlertsBindingOption:@YES}];
[self.table bind:@"selectionIndexPaths" toObject:self.treeController withKeyPath:@"selectionIndexPaths" options:@{}];
[self.table bind:@"sortDescriptors" toObject:self.treeController withKeyPath:@"sortDescriptors" options:@{}];
:
DataNode *node = [[DataNode alloc] init];
node.firstText = [NSString stringWithFormat:@"1 - %d", i1];
node.secondText = [NSString stringWithFormat:@"2 - %d", i1];
NSIndexPath *loc = [NSIndexPath indexPathWithIndex:self.contents.count]; // appends to end of list
[self.treeController insertObject:node atArrangedObjectIndexPath:loc];
将节点添加到树的根目录:
-(NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
return 0; // never called (due to using NSTreeController)
}
-(id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
return nil; // never called (due to using NSTreeController)
}
-(BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
return NO; // never called (due to using NSTreeController)
}
-(id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
DataNode *node = [item representedObject];
return [node valueForKey:tableColumn.identifier];
}
由于我的NSOutlineView是基于单元格的,我还一直在实现DataSource方法,以便为单元格提供值,因为我无法弄清楚如何为此进行绑定:
objectValueForTableColumn
firstText
方法假设表格列的标识符分别设置为secondText
和id
。