Skip to content

Instantly share code, notes, and snippets.

@jlindsey
Created July 29, 2010 20:55
Show Gist options
  • Save jlindsey/499215 to your computer and use it in GitHub Desktop.
Save jlindsey/499215 to your computer and use it in GitHub Desktop.
Select an image file using a sheet in Cocoa
NSArray *allowedImageFileExtensions = [NSArray arrayWithObjects:@"png",@"jpg",@"jpeg",@"gif",@"bmp",nil];
// ...
- (IBAction)displayImagePickerSheet:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:allowedImageFileExtensions];
[panel setDirectory:NSHomeDirectory()];
[panel setAllowsMultipleSelection:NO];
[panel setCanChooseDirectories:NO];
[panel setCanChooseFiles:YES];
[panel setResolvesAliases:YES];
[panel beginSheetModalForWindow:window completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton) {
// We aren't allowing multiple selection, but NSOpenPanel still returns
// an array with a single element.
NSURL *imagePath = [[panel URLs] objectAtIndex:0];
NSImage *image = [[NSImage alloc] initWithContentsOfURL:imagePath];
NSLog(@"Image: %@", image);
[image release];
} else {
[panel close];
}
}];
}
@peterpaulis
Copy link

[panel setAllowedFileTypes:[NSImage imageFileTypes]];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment