给定表示的模型对象NSTreeController
,如何在树中找到它们的索引路径并随后选择它们?这似乎是一个非常明显的问题,但我似乎找不到任何参考。有任何想法吗?
问问题
4317 次
2 回答
19
没有“简单”的方法,您必须遍历树节点并找到匹配的索引路径,例如:
目标-C:
类别
@implementation NSTreeController (Additions)
- (NSIndexPath*)indexPathOfObject:(id)anObject
{
return [self indexPathOfObject:anObject inNodes:[[self arrangedObjects] childNodes]];
}
- (NSIndexPath*)indexPathOfObject:(id)anObject inNodes:(NSArray*)nodes
{
for(NSTreeNode* node in nodes)
{
if([[node representedObject] isEqual:anObject])
return [node indexPath];
if([[node childNodes] count])
{
NSIndexPath* path = [self indexPathOfObject:anObject inNodes:[node childNodes]];
if(path)
return path;
}
}
return nil;
}
@end
迅速:
延期
extension NSTreeController {
func indexPathOfObject(anObject:NSObject) -> NSIndexPath? {
return self.indexPathOfObject(anObject, nodes: self.arrangedObjects.childNodes)
}
func indexPathOfObject(anObject:NSObject, nodes:[NSTreeNode]!) -> NSIndexPath? {
for node in nodes {
if (anObject == node.representedObject as! NSObject) {
return node.indexPath
}
if (node.childNodes != nil) {
if let path:NSIndexPath = self.indexPathOfObject(anObject, nodes: node.childNodes)
{
return path
}
}
}
return nil
}
}
于 2012-01-29T02:43:59.517 回答
-1
为什么不使用 NSOutlineView 来获取这样的父项:
NSMutableArray *selectedItemArray = [[NSMutableArray alloc] init];
[selectedItemArray addObject:[self.OutlineView itemAtRow:[self.OutlineView selectedRow]]];
while ([self.OutlineView parentForItem:[selectedItemArray lastObject]]) {
[selectedItemArray addObject:[self.OutlineView parentForItem:[selectedItemArray lastObject]]];
}
NSString *selectedPath = @".";
while ([selectedItemArray count] > 0) {
OBJECTtype *singleItem = [selectedItemArray lastObject];
selectedPath = [selectedPath stringByAppendingString:[NSString stringWithFormat:@"/%@", singleItem.name]];
selectedItemArray removeLastObject];
}
NSLog(@"Final Path: %@", selectedPath);
这将输出:./item1/item2/item3/...
我假设您正在这里寻找文件路径,但您可以调整您的数据源可能代表的任何内容。
于 2014-02-11T21:41:26.507 回答