已编辑以给出修改后的答案...
显然,一旦给定容器的父对象被折叠,就没有简单的方法来恢复给定容器是展开还是折叠。很明显,大纲视图的内部工作方式会记住一些东西——可能就像存储单元格视图的显示按钮单元格的状态一样简单,或者它可能在树控制器或其节点中设置一个标志——但无论如何都没有直接编程接口。我怀疑您必须在模型对象中跟踪它。
为此,向模型项添加一个布尔属性,例如:
@property BOOL currentlyExpanded;
然后您需要实现两个委托方法outlineViewItemDidExpand: 和outlineViewItemWillCollapse:,就像这样(假设您使用树形控制器作为大纲视图):
- (void)outlineViewItemDidExpand:(NSNotification *)notification {
NSTreeNode * node = [notification.userInfo objectForKey:@"NSObject"];
NSOutlineView * ov = notification.object;
MyModelItem * item = [node representedObject];
/*
because we can only expand a visible container, we merely note
that this container is now expanded in our view. This will be
called for every container that is expanded, so we don't have to
think about it much.
*/
item.currentlyExpanded = YES;
}
- (void)outlineViewItemWillCollapse:(NSNotification *)notification {
NSTreeNode * node = [notification.userInfo objectForKey:@"NSObject"];
NSOutlineView * ov = notification.object;
MyModelItem * item = [node representedObject];
/*
Elements are collapsed from top to bottom. A collapsed parent
means the collapse started someplace farther up the chain than
our current item, so the expansion state of the current item is
not going to change unless the option key is held down, or you
implement a collapseItem:collapseChildren: with the second
parameter as YES. This accounts for the first; you'll have to
deal with the second in code.
*/
BOOL optionKeyIsDown = [[NSApp currentEvent] modifierFlags] && NSEventModifierFlagOption;
if ([ov isItemExpanded:[node parentNode]] || optionKeyIsDown) {
item.currentlyExpanded = NO;
}
}
这些应该使模型项属性currentlyExpanded 与大纲视图的内部扩展表(无论是什么)同步。如果您想引用它或将其存储在数据库中,您可以直接从模型对象中访问它。
我处理位掩码的方式引发了警告,但我懒得修复它...
在编辑后保留最后一部分,因为我认为这是很好的信息...
通常您不必担心这些; NSOutlineView 会自行“做正确的事”。如果用户点击了一个容器的展开三角形然后重新打开它,所有的子容器都将保持它们的展开/折叠状态;如果用户选项单击控制三角形,所有子容器将被标记为展开或折叠(取决于用户是选项打开还是选项关闭父容器)。除非您想要一些特殊的行为(通常会在委托方法 outlineView:shouldCollapseItem: 和 outlineView:shouldExpandItem: 中设置),否则不要打扰它。
如果您尝试跨应用调用保留展开状态,请将 NSOutlineView 属性 autosaveExpandedItems 设置为 true。无需记账...