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];
}
}];
}
@jlindsey
Copy link
Author

This will allow you to display an image picker sheet in Objective-C / Cocoa. Of note, this uses the new 10.6 beginSheetModalForWindow:completionHandler: method which takes a closure as its second argument. Much preferable in my opinion to passing @selectors around everywhere and having to keep track of what protocols your controllers should implement.

This example is for selecting an image, but you could repurpose this example for any kind of file.

@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