如何让我的用户上传照片并设置好图像的图像
- (IBAction)chooseFile:(id)sender {
int i; // Loop counter.
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* files = [openDlg filenames];
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSString* fileName = [files objectAtIndex:i];
// Do something with the filename
[customButtonImg setImage:[NSImage imageNamed:fileName]];
}
}
}
最佳答案
NSOpenPanel* openDlg = [NSOpenPanel openPanel]
[openDlg setPrompt:@"Select"];
NSArray* imageTypes = [NSImage imageTypes];
[openDlg setAllowedFileTypes:imageTypes];
[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)
{
youimageView.image = img;
[img release];
}
else
{
youimageView.image = nil;
NSAlert *alert = [[NSAlert alloc]init];
[alert setMessageText:@"Application Message"];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert setInformativeText:@"Select Only Image"];
[alert beginSheetModalForWindow:self.view.window
modalDelegate:self didEndSelector:nil contextInfo:nil];
}
NSLog(@"%@",filePath);
//do something with the file at filePath
}
}];
关于objective-c - 打开文件对话框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7466717/