[英]How to select a file in cocoa
單擊選擇按鈕后如何選擇文件? 當我單擊選擇按鈕時,應該打開一個彈出窗口,我可以從硬盤中選擇文件。
-(IBAction)select:(id)sender{
NSOpenPanel* dlg =[NSOpenPanel openPanel];
[dlg setCanChooseFiles:YES];
[dlg setCanChooseDirectories:YES];
}
編輯 (發布代碼后):
您實際上並沒有打開面板,因此需要以下內容:
NSInteger button = [dlg runModal];
if (button == NSFileHandlingPanelOKButton)
{
NSURL *chosenURL = [[dlg URLs] objectAtIndex:0];
// Do something with chosen file
}
編輯 : NSOpenPanel
只能以run modally
。因此,您need
[YourNSOpenPanelObject runModal]
。
請參閱NSOpenPanel鏈接。
使用NSOpenPanel
。 下面給出了選擇帶有filteration
NSImage
示例:
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
//[openDlg setCanChooseFiles:YES];
//[openDlg setCanChooseDirectories:NO];
[openDlg setPrompt:@"Select"];
NSArray* imageTypes = [NSImage imageTypes];
[openDlg setAllowedFileTypes:imageTypes];
//[openDlg setAllowsOtherFileTypes:NO];
[openDlg beginWithCompletionHandler:^(NSInteger result){
NSArray* files = [openDlg filenames];
NSData *imgData;
for(NSString* filePath in files)
{
NSURL *url = [[NSURL alloc]initFileURLWithPath:filePath];
NSImage *img;
if(url)
{
img = [[NSImage alloc]initWithContentsOfURL:url];
imgData = [NSData dataWithContentsOfURL:url];
[url release];
}
if(img)
{
imgSubCategoryView.image = img;
[img release];
}
else
{
imgSubCategoryView.image = nil;
NSAlert *alert = [[NSAlert alloc]init];
[alert setMessageText:@"Application Message"];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert setInformativeText:@"Select Only Image"];
[alert beginSheetModalForWindow:_window
modalDelegate:self didEndSelector:nil contextInfo:nil];
}
}
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.