NSOpenPanel - Set file type?

Just see what I will use to allow only certain files (images for now)

setFileTypesArray returns

NSOpenPanel may not respond to -setFileTypesArray:

and then the panel does not open at all. Here is my code:

  NSArray * fileTypes = [NSArray arrayWithObjects:@"png",@"tiff",@"baz",nil]; NSLog(@"Button Pressed"); [textField setStringValue:@"Test"]; int i; // Loop counter. NSOpenPanel* openDlg = [NSOpenPanel openPanel]; [openDlg setCanChooseFiles:YES]; [openDlg setFileTypesArray:fileTypes]; 

Thanks.

+6
cocoa
source share
6 answers

You are looking for a delegate method from an NSSaveOpenPanel delegate

 -(BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename { NSString* ext = [filename pathExtension]; if (ext == @"" || ext == @"/" || ext == nil || ext == NULL || [ext length] < 1) { return TRUE; } NSLog(@"Ext: '%@'", ext); NSEnumerator* tagEnumerator = [[NSArray arrayWithObjects:@"png", @"tiff", @"jpg", @"gif", @"jpeg", nil] objectEnumerator]; NSString* allowedExt; while ((allowedExt = [tagEnumerator nextObject])) { if ([ext caseInsensitiveCompare:allowedExt] == NSOrderedSame) { return TRUE; } } return FALSE; } 

Then set the delegate to the "self" panel or wherever you define this method above.

+13
source share

How about [openDlg setAllowedFileTypes:fileTypes]; ?

+27
source share

You might want to check

 [panel setAllowedFileTypes:[NSImage imageTypes]]; 

Or implement the NSOpenSavePanelDelegate delegate

and implement

 - (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url { NSString * fileExtension = [url pathExtension]; if (([fileExtension isEqual: @""]) || ([fileExtension isEqual: @"/"]) || (fileExtension == nil)) { return YES; } NSSet * allowed = [NSSet setWithArray:@[@"png", @"tiff", @"jpg", @"gif", @"jpeg"]]; return [allowed containsObject:[fileExtension lowercaseString]]; } 
+10
source share

The method you are looking for is setAllowedFileTypes - see the docs for the parent class, NSSavePanel .

+8
source share

This worked for me:

  NSArray * fileTypes = [NSArray arrayWithObjects:@"png",@"jpg",@"tiff",nil]; [openDlg setAllowedFileTypes:fileTypes]; 
+2
source share

my two cents for osx / swift 5 (you can specify a title and transfer it to the "pictures" folder.

 override func showChooseImageDialog(title: String){ let openPanel = NSOpenPanel() openPanel.canChooseFiles = false openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.title = title openPanel.canChooseDirectories = false openPanel.canChooseFiles = true openPanel.allowedFileTypes = NSImage.imageTypes openPanel.directoryURL = URL(fileURLWithPath: picturesDir() ) openPanel.beginSheetModal(for:self.view.window!) { (response) in if response == .OK { let selectedPath = openPanel.url!.path // do whatever you what with the file path } openPanel.close() } } 
0
source share

All Articles