2011-09-09 7 views
1

이렇게하는 것이 일반적인 일일 수도 있지만 워드 프로세서와 구글은 나를 실패하게합니다. NSMenu의 모든 항목을 사전 순으로 정렬하고 싶습니다. 하위 메뉴가있는 모든 항목을 먼저 정렬해야합니다. 지금 NSComparator를 사용하여 사용자 지정 코드를 작성하고 있지만이 코드가 내장되어 있는지 묻고 싶습니다. 경로 파인더가 수행합니다. 나는 Finder가 그것을 할 수도 있다고 생각한다.NSMenuItem을 사전 순으로 정렬하고 서브 메뉴가 있는지 여부에 따라?

답변

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]; 
     } 
    } 
} 
관련 문제