Created
July 29, 2010 20:55
-
-
Save jlindsey/499215 to your computer and use it in GitHub Desktop.
Select an image file using a sheet in Cocoa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
}]; | |
} |
[panel setAllowedFileTypes:[NSImage imageFileTypes]];
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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@selector
s 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.