How can I preset the filename in NSSavePanel?

余生长醉 提交于 2019-12-08 16:03:34

问题


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?


回答1:


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];



回答2:


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


来源:https://stackoverflow.com/questions/6673386/how-can-i-preset-the-filename-in-nssavepanel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!