強火で進め

このブログではプログラム関連の記事を中心に書いてます。

ほぼ日、MacのGUI - Pop Up(ポップアップリストからの選択)

ポップアップリストからの選択を行うサンプルです。NSPopUpButtonクラスを主に使います。

主にInterfaceBuilderでの作業になります。LibraryウィンドウのLibrary → Cocoa → Applicationに有る「Menu Item」などを追加して必要なリストを作成します。Itemを削除する場合はホップアップ外にドラッグすればOKです。

主なメソッドは以下となります。

メソッド 説明
- (void)selectItemWithTitle:(NSString *)title タイトルを指定してItemを選択
- (void)selectItemAtIndex:(NSInteger)index インデックスを指定してItemを選択
- (NSString *)titleOfSelectedItem 選択されているItemのタイトルを取得
- (NSInteger)indexOfSelectedItem 選択されているItemのインデックスを取得。インデックスは0からスタートで上から順番に振られます。セパレータもカウントされます

主な処理は以下の様になります。

- (IBAction)selectedPopUp:(id)sender
{
	NSLog(@"%@(index=%d) が選択されました\n", 
		  [popUpButton titleOfSelectedItem], [popUpButton indexOfSelectedItem]);
}

- (IBAction)pushButton:(id)sender
{
	// タイトルが "Data1" のItemを選択する
	[popUpButton selectItemWithTitle:@"Data1"];
}

公式の解説はこちら。

NSPopUpButton Class Reference
http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPopUpButton_Class/Reference/Reference.html

日本語の解説が良い人はこちらのSatoshi Oomoriさんのページを参照下さい。

http://www.oomori.com/cocoafw/ApplicationKit/NSPopUpButton/index.html
※注記
http://www.oomori.com/cocodesu/index.html

ソースコードこちら