選択インデックスがNSWindowControllerサブクラスのプロパティにバインドされているNSPopupButtonがあります。IBでは、ボタンはいくつかの項目で始まります。プロパティの値はNSUserDefaultsから取得され、最初にインスタンス化されたときのNSPopupButtonのアイテムの数よりも多い場合があります。これにより、リストの最後に空白の項目が挿入されます。ボタンにアイテムを追加しても、自動的に作成された空白のアイテムはまだそこにあります。しかし、私が選択を行うと、それは消えます。選択する前に空白のアイテムのタイトルを変更しても、アイテムは消えます。
私は問題をこのコードにまで絞り込みました:
@interface PopUpWindowController : NSWindowController {
NSUInteger popUpValue;
IBOutlet NSPopUpButton *popUp;
}
@property NSUInteger popUpValue; //popUp's Selected Index is bound to this property
-(IBAction)addItemsToPopUp:(id)sender;
-(IBAction)nameBlankItem:(id)sender;
@end
@implementation PopUpWindowController
@synthesize popUpValue;
-(id)init {
if (self = [super initWithWindowNibName:@"PopUpWindow"]) {
popUpValue = 5; //In my real program this comes from NSUserDefaults
}
return self;
}
-(IBAction)addItemsToPopUp:(id)sender {
//Add three items to popUp
NSUInteger lastNewItem = [popUp numberOfItems] + 3;
for (NSUInteger newItem = [popUp numberOfItems]; newItem < lastNewItem; newItem++) {
[popUp addItemWithTitle:[NSString stringWithFormat:@"%d", newItem + 1]];
}
self.popUpValue = 5;
}
-(IBAction)nameBlankItem:(id)sender {
NSArray *items = [popUp itemArray];
for (NSUInteger i = 0; i < [items count]; i++) {
if (![[[items objectAtIndex:i] title] length]) {
//item title is blank so set it to the item number
[[items objectAtIndex:i] setTitle:[NSString stringWithFormat:@"%d", i + 1]];
}
}
}
@end
ウィンドウが最初に表示されたときのポップアップのメニューは次のとおりです(IBには「1」、「2」、「3」という名前の3つの項目があります)。
こちらはお電話後ですaddItemsToPopUp:
こちらはお電話後ですnameBlankItem:
それから私はaddItemsToPopUp:
再び電話をしました:
これで、最終的に選択を行い、メニューを再度ポップアップします。
どこに行った4
の?
私の実際のプログラムでは、メニュー項目を「1」..「n」(nは計算されたNSArray内の項目の数で定義されます)にします。私は別のアプローチを受け入れていますが、ソリューションが引き続きNSPopupButtonを使用することを望んでいます。
(重要な場合は、OS X10.5.8ではXcode3.1.2を使用していますが、OS X10.6.8ではXcode3.2でもテストしています。)