Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a file selector/opener in cocoa with Interface Builder?

I'm wondering how to make a button or input field in Interface Builder react in such a way that on click it opens a file dialog and lets you select one or more files and puts them into a specified array/table...

Once the button is pushed and files are chosen (this seems a like quite trivial thing) I guess it will already contain some sort of array (like an array with paths to the selected files) so I've got that covered.. I only need to know how to link the button to a file selector and in what way the file selector delivers the files to me (or paths to the files) so I can redirect them to the array

Is there an easy way to do this, and more importantly; is there a file selector thingie or do I have to do this with XCode instead of Interface builder?

like image 204
xaddict Avatar asked Jan 26 '09 23:01

xaddict


1 Answers

I found this page when looking up, how to open up a file open box in Cocoa. With the release of OS X 10.7 a lot of the samples that is linked to is now deprecated. So, here is some sample code that will save you some compiler warnings:

// -----------------
// NSOpenPanel: Displaying a File Open Dialog in OS X 10.7
// -----------------

// Any ole method
- (void)someMethod {
  // Create a File Open Dialog class.
  NSOpenPanel *openDlg = [NSOpenPanel openPanel];

  // Set array of file types 
  NSArray<NSString*> *fileTypesArray = @[@"jpg", @"gif", @"png"];

  // Enable options in the dialog.
  [openDlg setCanChooseFiles:YES];    
  [openDlg setAllowedFileTypes:fileTypesArray];
  [openDlg setAllowsMultipleSelection:YES];

  // Display the dialog box.  If OK is pressed, process the files.
  if ([openDlg runModal] == NSModalResponseOK) {
    // Get list of all files selected
    NSArray<NSURL*> *files = [openDlg URLs];

    // Loop through the files and process them.
    for (NSURL *file in files) {
      // Do something with the filename.
      NSLog(@"File path: %@", [file path]);
    }
  }
}
like image 187
archieoi Avatar answered Sep 19 '22 09:09

archieoi