按字母顺序排序NSMenuItems,以及它们是否有子菜单?

时间:2011-09-09 21:06:56

标签: objective-c

似乎这可能是常见的事情,但文档和谷歌让我失望。我希望NSMenu中的所有项目按字母顺序排序。我还想首先对所有具有子菜单的项目进行排序。我现在正在使用NSComparator编写自定义代码,但我想我会问,看看它是否内置了? Path Finder做到了。我认为Finder也可以这样做。

1 个答案:

答案 0 :(得分:4)

我已经制作了以下代码,所以我猜我已经回答了我自己的问题:

-(void)sortMenu:(NSMenu*)menu
{
    // [CH] Get an array of all menu items.
    NSArray* items = [menu itemArray];
    [menu removeAllItems];
    // [CH] Sort the array
    NSSortDescriptor* alphaDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
    NSSortDescriptor* submenuDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"hasSubmenu" ascending:NO];
    items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:submenuDescriptor,alphaDescriptor, nil]];
    // [CH] ok, now set it back.
    for(NSMenuItem* item in items){
        [menu addItem:item];
        /**
         * [CH] The following code fixes NSPopUpButton's confusion that occurs when
         * we sort this list. NSPopUpButton listens to the NSMenu's add notifications
         * and hides the first item. Sorting this blows it up.
        **/
        if(item.isHidden){
            item.hidden = false;
        }
        // [CH] While we're looping, if there's a submenu, go ahead and sort that, too.
        if(item.hasSubmenu){
            [self sortMenu:item.submenu];
        }
    }
}