6

Does anyone know how to preselect a file in the NSOpenPanel dialog?

This has been asked several times before, but none of those questions were answered with a working solution. Setting nameFieldStringValue has no effect as the open dialog does not have a textfield for the user to type in a name. Setting the directoryURL only sets the current directory in the dialog.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
hvanbrug
  • 1,291
  • 2
  • 12
  • 25

1 Answers1

8

Try like this:-

NSOpenPanel *op=[NSOpenPanel openPanel];
[op setDirectoryURL:[NSURL URLWithString:@"file://localhost/Users/Home/Desktop/yourfile.sh/"]];
[op runModal];
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • As I indicated in my question, setting the directoryURL only makes the dialog show that directory. It does not actually select the file. – hvanbrug Sep 21 '13 at 23:48
  • I just ran a test where I hard coded the path and you are correct. It does select the filename. That must mean that in my regular logic I am not properly building the path. Thank-you for the confirmation. – hvanbrug Sep 22 '13 at 09:21
  • 2
    It turns out that my problem was using `[panel setDirectoryURL: [NSURL URLWithString: path]];` instead of `[panel setDirectoryURL: [NSURL fileURLWithPath: path]];` – hvanbrug Sep 22 '13 at 09:48
  • Note that this does *not* work on 10.6, the first OS X version for which this API is available; instead it treats the file if it were an empty directory. (It works fine on 10.7 and 10.8, and I imagine on 10.9 though I haven't tested it.) – Nicholas Riley Jan 26 '14 at 05:01
  • 1
    Interesting that there is an internal difference between URLWithString and fileURLWithPath which produce identical output in NSLog. – SG1 Feb 24 '14 at 22:14