NSToolbarItemGroup - 不起作用?

时间:2013-04-11 13:17:50

标签: cocoa appkit nstoolbar nstoolbaritem

NSToolbarItemGroup记录在案here。关于它,我找不到更多的东西!

我正在尝试使用它,看看它的外观。我的代码基本上是直接从文档中提取的。但是,我从未在工具栏中看到“组”。代码运行,项目被添加到工具栏中,但它只是不可见?!

有没有人成功使用它?使用最新的XCode环境是10.8.3。

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
    return [NSArray arrayWithObject:@"GroupItem"];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
    return [NSArray arrayWithObject:@"GroupItem"];
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem *item1 = [[NSToolbarItem alloc] initWithItemIdentifier:@"Item1"];
    NSToolbarItem *item2 = [[NSToolbarItem alloc] initWithItemIdentifier:@"Item2"];
    [item1 setImage:[NSImage imageNamed:NSImageNameQuickLookTemplate]];
    [item2 setImage:[NSImage imageNamed:NSImageNameQuickLookTemplate]];
    [item1 setLabel:@"Prev"];
    [item2 setLabel:@"Next"];

    NSToolbarItemGroup *group = [[NSToolbarItemGroup alloc] initWithItemIdentifier:@"GroupItem"];
    [group setSubitems:[NSArray arrayWithObjects:item1, item2, nil]];

    [group setLabel:@"Navigate"];

    return group;
}

1 个答案:

答案 0 :(得分:5)

我也碰到了这个。它很烦人。我的问题是我需要明确设置每个项目和包含组的minSizemaxSize。也许这会奏效:

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem* retVal = nil;

    if ([@"GroupItem" isEqual: itemIdentifier])
    {
        NSToolbarItem *item1 = [[NSToolbarItem alloc] initWithItemIdentifier:@"Item1"];
        NSToolbarItem *item2 = [[NSToolbarItem alloc] initWithItemIdentifier:@"Item2"];

        NSToolbarItemGroup *group = [[NSToolbarItemGroup alloc] initWithItemIdentifier:@"GroupItem"];
        [group setSubitems:[NSArray arrayWithObjects:item1, item2, nil]];

        item1.image = [NSImage imageNamed:NSImageNameQuickLookTemplate];
        item1.minSize = item1.image.size;
        item1.maxSize = item1.image.size;
        item1.label = @"Prev";

        item2.image = [NSImage imageNamed:NSImageNameQuickLookTemplate];
        item2.minSize = item2.image.size;
        item2.maxSize = item2.image.size;
        item2.label = @"Next";


        group.label = @"Navigate";
        NSSize minSize = NSZeroSize;
        NSSize maxSize = NSZeroSize;
        for (NSToolbarItem* item in group.subitems)
        {
            minSize.width += item.minSize.width;
            minSize.height = MAX(minSize.height, item.minSize.height);
            maxSize.width += item.maxSize.width;
            maxSize.height = MAX(maxSize.height, item.maxSize.height);
        }
        group.minSize = minSize;
        group.maxSize = maxSize;

        retVal = group;
    }
    return retVal;
}

这对我来说似乎很愚蠢,这不是默认行为,但这并没有阻止我浪费半个小时搞清楚。另外,请注意订购 - 如果您在将子项目放入组的子项集合之前设置子项目最小和最大尺寸,该组将重置您的尺寸为32x32 。哎呀。