Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preset the filename in NSSavePanel?

Tags:

cocoa

macruby

NSSavePanel used to have a runModalForDirectory:file: method which let you preset the directory and filename for a save panel. But that is deprecated in 10.6

When creating an NSSavePanel, how can I preset the filename without using the deprecated method?

like image 636
Michael Johnston Avatar asked Jul 13 '11 02:07

Michael Johnston


2 Answers

Use the setNameFieldStringValue: method, which was added in 10.6, before running the save panel. If you want to set the default directory too, you will need the setDirectoryURL: method, also added in 10.6.

NSString *defaultDirectoryPath, *defaultName;
NSSavePanel *savePanel;
...
[savePanel setNameFieldStringValue:defaultName];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:defaultDirectoryPath]];
[savePanel runModal];
like image 67
ughoavgfhw Avatar answered Oct 18 '22 04:10

ughoavgfhw


There is a method that I didn't notice at first, NSSavePanel#setNameFieldStringValue, which sets the filename.

here is a complete example in macruby syntax:

def run_save_settings_dialog(sender)
  dialog = NSSavePanel.savePanel
  dialog.title = "Save Settings"
  dialog.canCreateDirectories = true
  dialog.showsHiddenFiles = true
  dialog.nameFieldStringValue = "MyFile"
  dialog.canChooseFiles = true
  dialog.canChooseDirectories = false
  dialog.allowsMultipleSelection = false
  dialog.setDirectoryURL NSURL.fileURLWithPath("some/path")
  if dialog.runModal == NSFileHandlingPanelOKButton
    save_settings(dialog.URL)
  end
end

def save_settings(file_url)
  File.open(file_url.path, 'w') {|f| f.write "Stuff" }
end
like image 39
Michael Johnston Avatar answered Oct 18 '22 05:10

Michael Johnston