【问题标题】:How to fill the URLs array of the NSOpenPanel with absolute file path?如何用绝对文件路径填充 NSOpenPanel 的 URLs 数组?
【发布时间】:2022-08-04 03:11:13
【问题描述】:

我正在尝试创建一个面板,让用户选择保存文件的路径。当用户从显示相对路径(即 /folder)的面板中选择一个目录时,URLs 属性包含 /folder。当用户选择显示完整路径的目录时,panelURLs 属性包含完整路径(即 /User/name/folder)。即使用户面板显示相对路径,如何确保 URLs 属性肯定包含完整路径?

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:NO];
[panel setCanChooseDirectories:YES];
[panel setAllowsMultipleSelection:NO]; // yes if more than one dir is allowed

NSInteger clicked = [panel runModal];

NSArray<NSURL *> *URLs;
if (clicked == NSFileHandlingPanelOKButton) {
    URLs = [panel URLs];
}
else{
    URLs = [NSArray arrayWithObject:[NSURL URLWithString:[NSString stringWithFormat:@\"file://%s/\", getenv(\"HOME\")]]];
}
for (NSURL *url in URLs) { // When user clicks cancel, [panel URLs] is empty
    NSString *selectedDirectoryPath = [url.absoluteString substringFromIndex:6];
//  NSString *selectedDirectoryPath = [url path];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *sourceFilePath = [NSString stringWithFormat:@\"%@/%@\", NSHomeDirectory(), _fileName];
    NSString *destFilePath = [NSString stringWithFormat:@\"%@%@\", selectedDirectoryPath, _fileName];
}

我以为我可以在 url 上使用 path 实例属性,但是一旦用户单击 OK 到带有 NSFileHandlingPanelOKButton 的文件路径,数组就会被填充。

编辑:我发现一个回复建议在 NSOpenPanel URL to string 中使用 beginSheetModalForWindow ,但是您如何使用此功能?

标签: objective-c macos relative-path absolute-path nsopenpanel


【解决方案1】:

默认情况下,我使用 setDirectoryURL 将面板打开到根文件夹。这将有助于确保它返回绝对路径,否则返回相对路径。

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setDirectoryURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:///"]]];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2015-08-29
    • 2021-10-18
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多