強火で進め

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

ほぼ日、MacのGUI - OpenPanel(開くファイルの指定、オープンパネル)

NSOpenPanel(フォルダやファイルの選択)のサンプルです。

ここではパネルが親ウィンドウから独立した状態で表示される runModalForTypes: メソッドの解説をします。
親ウィンドウにくっついた状態で表示される
beginSheetForDirectory:file:types:modalForWindow:modalDelegate:didEndSelector:contextInfo: メソッドについての解説はこちらを参照下さい。

	// 開けるファイルを拡張子で制限する
	NSArray *fileTypes = [NSArray arrayWithObjects:@"txt", nil];
	// nil を指定するとすべてのファイルが選択可能
	result = [openPanel runModalForTypes:fileTypes];

runModalForTypes:メソッドの引数にNSArrayで選択できる拡張子を指定します。
nilを指定するとすべてのファイルが選択可能です。

サンプルのソースコードではtxtの拡張子を持ったファイルのみ選択できます。
すべてのファイルを選択したい場合は

	result = [openPanel runModalForTypes:nil];

のようにして下さい。

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

- (IBAction)pushButton:(id)sender;
{
	NSOpenPanel* openPanel;
	NSArray *fileTypes = [NSArray arrayWithObjects:@"txt", nil]; // 開けるファイルを拡張子で制限する
	int result;
	
	openPanel = [NSOpenPanel openPanel];
	
	result = [openPanel runModalForTypes:fileTypes]; // nil を指定するとすべてのファイルが選択可能
	
	if (result == NSOKButton) {
		NSLog(@"OKボタンが押されました\n");
		NSLog(@"選択ディレクトリ : %@\n", [openPanel directory]);
		NSLog(@"選択ファイル : %@\n", [openPanel filename]);
	}
	else if (result == NSCancelButton) {
		NSLog(@"Cancelボタンが押されました\n");
	}
}

公式の解説はこちら。

NSOpenPanel Class Reference
http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSOpenPanel_Class/Reference/Reference.html

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

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

ソースコードこちら