单击选择按钮后如何选择文件?当我单击选择按钮时,它应该会打开一个弹出窗口,我可以从我的硬盘中选择文件。
-(IBAction)select:(id)sender{
NSOpenPanel* dlg =[NSOpenPanel openPanel];
[dlg setCanChooseFiles:YES];
[dlg setCanChooseDirectories:YES];
}
单击选择按钮后如何选择文件?当我单击选择按钮时,它应该会打开一个弹出窗口,我可以从我的硬盘中选择文件。
-(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
. 下面给出了选择NSImage
的示例:filteration
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];
}
}
}];