实现这个委托并使用类似的东西:
- (void)outlineViewItemDidExpand:(NSNotification *)notification{
for (id parent in list) {
if ([notification.userInfo objectForKey:@"NSObject"] == parent) {
continue;
}
[notification.object collapseItem:parent];
}
}
这parent
是顶级项目数组,如您的示例 Folder1 和 Folder2。
编辑:
Appdelegate.h
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property(strong) NSDictionary *firstParent;
@property(strong) NSDictionary *secondParent;
@property(strong) NSArray *list;
@end
Appdelegate.m
@implementation AppDelegate
@synthesize firstParent;
@synthesize secondParent;
@synthesize list;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
}
- (id)init {
self = [super init];
if (self) {
firstParent = [NSDictionary dictionaryWithObjectsAndKeys:@"A",@"parent",
[NSArray arrayWithObjects:@"Apple",@"Aeroplane", nil],@"children", nil];
secondParent = [NSDictionary dictionaryWithObjectsAndKeys:@"B",@"parent",
[NSArray arrayWithObjects:@"Ball",@"Baloon", nil],@"children", nil];
list = [NSArray arrayWithObjects:firstParent,secondParent, nil];
}
return self;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item{
if ([item isKindOfClass:[NSDictionary class]]) {
return YES;
}
else {
return NO;
}
}
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item{
if (item == nil) { //item is nil when the outline view wants to inquire for root level items
return [list count];
}
if ([item isKindOfClass:[NSDictionary class]]) {
return [[item objectForKey:@"children"] count];
}
return 0;
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item{
if (item == nil) { //item is nil when the outline view wants to inquire for root level items
return [list objectAtIndex:index];
}
if ([item isKindOfClass:[NSDictionary class]]) {
return [[item objectForKey:@"children"] objectAtIndex:index];
}
return nil;
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)theColumn byItem:(id)item
{
if ([[theColumn identifier] isEqualToString:@"children"]) {
if ([item isKindOfClass:[NSDictionary class]]) {
return [NSString stringWithFormat:@"%ld kids",[[item objectForKey:@"children"] count]];
}
return item;
}
else{
if ([item isKindOfClass:[NSDictionary class]]) {
return [item objectForKey:@"parent"];
}
}
return nil;
}
再加上一种方法写在上面。
并将 NSOutlineView 的委托设置为 IB 中的 AppDelegate。