pvinis
pvinis

Reputation: 4139

Add item from finder

I have a table with the classic + - buttons underneath it. (on mac) I want to press the + button, and open a little finder to select a file, to add it on the table.

How can I do that? I searched the developer reference, but didn't find it..

Upvotes: 1

Views: 228

Answers (1)

user557219
user557219

Reputation:

Use NSOpenPanel.

For a guide on dealing with files and using open panels, see the Application File Management guide.

For instance:

- (IBAction)addFile:(id)sender
{
    NSInteger result;
    NSArray *fileTypes = [NSArray arrayWithObject:@"html"];
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];

    [oPanel setAllowsMultipleSelection:YES];
    [oPanel setDirectory:NSHomeDirectory()];
    [oPanel setCanChooseDirectories:NO];
    result = [oPanel runModal];

    if (result == NSFileHandlingPanelOKButton) {
        for (NSURL *fileURL in [oPanel URLs]) {
            // do something with fileURL
        }
    }
}

Another example using a sheet:

- (IBAction)addFile:(id)sender
{
    NSArray *fileTypes = [NSArray arrayWithObject:@"html"];
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];

    [oPanel setAllowsMultipleSelection:YES];
    [oPanel setDirectory:NSHomeDirectory()];
    [oPanel setCanChooseDirectories:NO];
    [oPanel beginSheetModalForWindow:[self window]
        completionHandler:^(NSInteger result) {
        if (result == NSFileHandlingPanelOKButton) {
            for (NSURL *fileURL in [oPanel URLs]) {
                // do something with fileURL
            }
        }
    }];

}

Upvotes: 2

Related Questions