2011-09-09 7 views
1

これは一般的なことかもしれないが、ドキュメントとGoogleは私に失敗しているようだ。私はNSMenuのすべての項目をアルファベット順にソートしたいと思います。私はまた、サブメニューを持つすべてのアイテムを最初にソートしたいと思います。今はNSComparatorを使用してカスタムコードを書いていますが、これが組み込みであるかどうか尋ねてみました。パスファインダーはそれを行います。私はFinderもそうするかもしれないと思います。NSMenuItemsをアルファベット順にソートし、サブメニューを持つかどうかでソートしますか?

答えて

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]; 
     } 
    } 
} 
関連する問題