2012-06-23 86 views
0

我使用以下綁定排序NSPopUpButton:維護子菜單中NSPopUpButton

[arrayController bind:@"contentArray" toObject:self withKeyPath:@"displayElements" options:nil]; 
[popUpButton bind:@"content" toObject:arrayController withKeyPath:@"arrangedObjects" options:nil]; 
[popUpButton bind:@"contentValues" toObject:arrayController withKeyPath:@"arrangedObjects.title" options:nil]; 

displayElements是NSMenuItem

displayElements = [[NSMutableArray alloc] initWithObjects:[[NSMenuItem alloc]initWithTitle:@"one" action:nil keyEquivalent:@""], 
                   [[NSMenuItem alloc]initWithTitle:@"two" action:nil keyEquivalent:@""], 
                   [[NSMenuItem alloc]initWithTitle:@"three" action:nil keyEquivalent:@""], 
                   nil]; 

的NSMutable陣列和排序工作得很好。

現在的問題是,如果我的子菜單添加到任何菜單項目之後,我添加一個新的NSMenuItem到陣列控制器,子菜單先前添加的消失,如圖圖像下面:

之前添加新項:

enter image description here

enter image description here

添加新的項目後,

我使用的語句添加新NSMenuItem:

[arrayController addObject:[[NSMenuItem alloc]initWithTitle:[newItemTextField stringValue] action:nil keyEquivalent:@""]]; 

,當我們的元素進行排序相同的行爲被顯示。 任何想法解決這個問題??

+0

你如何添加子菜單:您可以通過包裝,增加了該子菜單陣列控制器的代碼做到這一點? –

+0

@Jacob這裏是我用來添加子菜單的代碼'[[popUpButton menu] setSubmenu:defaultSubMenu forItem:[popUpButton itemAtIndex:[indexValue intValue]]]'其中** popUpButton **是_NSPopUpButton_的出口和** indexValue **是_NSTextField_的出口,用戶從中輸入他/她想要添加子菜單的索引。 – rsharma

回答

0

如果不是將其添加到forItem:[popUpButton itemAtIndex:[indexValue intValue]]而是將它添加到arrayController中的項目中,會發生什麼?

我懷疑當你以後在ArrayController中添加一個菜單項時,綁定會導致NSPopUpMenu本身從NSArrayController中的值中創建新的NSMenuItems。而且這些數組控制器中的項目沒有子菜單,因爲您直接在彈出式按鈕中創建了它。

就像您在Array Controller中添加新項目一樣,我想您應該將子菜單添加到Array Controller中的項目中。

如果將子菜單添加到數組控制器中的項目中,則看不到子菜單出現在按鈕本身中,這可能意味着您需要再次觸發綁定,以便彈出按鈕將重建其菜單。 [arrayController willChangeValueForKey:@"arrangedObjects"];[arrayController didChangeValueForKey:@"arrangedObjects"];

+0

'[arrayController willChangeValueForKey:@「arrangedObjects」]; [[[arrayController arrangedObjects] objectAtIndex:[indexValue intValue]] setSubmenu:defaultSubMenu]; [arrayController didChangeValueForKey:@「arrangedObjects」];'這是你的意思是包裝,或者我只是誤解@Jacob – rsharma

+0

是的,這就是我的意思。 –

+0

它不工作。但是,正在添加子菜單(_I使用NSLog打印arrayController,我可以看到在console_上添加了一個子菜單)。但子菜單尚未顯示在彈出式按鈕中。有任何想法嗎? – rsharma