如何动态调整NSMenu的大小到其内容?

时间:2011-07-08 19:19:37

标签: cocoa osx-snow-leopard nsmenuitem nsmenu

我有像这样的标准NSMenu

initial menu

此菜单是使用以下代码创建的:

NSMenu *menu = [[NSMenu alloc] init];

    NSMenuItem *addMenuItem = [[NSMenuItem alloc] init];
    [addMenuItem setTitle:[NSString stringWithFormat:@"Upload"]];
    [addMenuItem setHidden:NO];
    [addMenuItem setRepresentedObject:contentType];
    [addMenuItem setTarget:self];
    [addMenuItem setAction:@selector(performSelectedDragOperation:)];
    [addMenuItem setTag:operation];
    [addMenuItem setEnabled:YES];

    [menu addItem:addMenuItem];

    NSMenuItem *alterMenuItem = [addMenuItem copy];
    [alterMenuItem setTitle:@"Upload in Folder"];
    [alterMenuItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
    [alterMenuItem setAlternate:YES];
    [menu addItem:alterMenuItem];
    [alterMenuItem release];

    [addMenuItem release];

    NSMenuItem *addMenuItem2 = [[NSMenuItem alloc] init];
    [addMenuItem2 setTitle:[NSString stringWithFormat:@"EditNewAndUpload"]];
    [addMenuItem2 setHidden:NO];
    [addMenuItem2 setRepresentedObject:contentType];
    [addMenuItem2 setTarget:self];
    [addMenuItem2 setAction:@selector(performSelectedDragOperation:)];
    [addMenuItem2 setTag:operation];
    [addMenuItem2 setEnabled:YES];

    [menu addItem:addMenuItem2];

    NSMenuItem *alterMenuItem2 = [addMenuItem2 copy];
    [alterMenuItem2 setTitle:@"EditNewAndUpload in Folder"];
    [alterMenuItem2 setKeyEquivalentModifierMask:NSAlternateKeyMask];
    [alterMenuItem2 setAlternate:YES];
    [menu addItem:alterMenuItem2];
    [alterMenuItem2 release];

    [addMenuItem2 release];

正如您所看到的,菜单中的每个选项都有一个“重复”项。当您按选项时显示该项目的副本(alt)键,菜单可见。

问题是菜单大小在显示备用菜单项时会发生变化,因为此菜单的标题大于原始标题,并且它永远不会恢复到原始大小,从而生成:

enter image description here

我知道如何解决它? 感谢

2 个答案:

答案 0 :(得分:2)

这是正常行为,你不应该担心它。如果您想要更改,file a bug

答案 1 :(得分:0)

您只需要更改NSMenuItem标题

[[appmenu itemAtIndex:0] setTitle:[NSString stringWithFormat:@“EditNewAndUpload  \ t \ t \ t \ t \ t“]];