16

我有一个 NSOpenPanel。但我想让它只能选择 PDF 文件。我正在寻找类似的东西:

// NOT WORKING 
NSOpenPanel *panel;

panel = [NSOpenPanel openPanel];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:[NSArray arrayWithObject:@"pdf"]];
int i = [panel runModalForTypes:nil];
if(i == NSOKButton){
    return [panel filenames];
}

我希望有人有一个解决方案。

4

2 回答 2

34

我注意到了几件事..更改setCanChooseDirectories为否。启用后,这表示文件夹是有效输入。这很可能不是您想要的功能。您可能还希望将允许的文件类型更改[NSArray arrayWithObject:@"pdf", @"PDF", nil]为区分大小写的系统。runModalForTypes应该是文件类型的数组。将您的代码更改为如下所示:

// WORKING :)
NSOpenPanel *panel;
NSArray* fileTypes = [NSArray arrayWithObjects:@"pdf", @"PDF", nil];
panel = [NSOpenPanel openPanel];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:NO];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:fileTypes];
int i = [panel runModal];
if(i == NSOKButton){
    return [panel URLs];
}

斯威夫特 4.2:

let fileTypes = ["jpg", "png", "jpeg"]
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedFileTypes = fileTypes
panel.beginSheetModal(for: window) { (result) in
    if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
         // Do something with the result.
         let selectedFolder = panel.urls[0]
         print(selectedFolder)
    }
}
于 2010-11-27T22:24:26.203 回答
2

你非常接近答案。

首先,摆脱它,[panel setCanChooseDirectories:YES]因此它不会允许目录。

然后,要么更改[panel runModalForTypes:nil][panel runModal]或删除对的调用[panel setAllowedFileTypes:]并将数组传递给[panel runModalForTypes:]

于 2010-11-27T22:24:56.723 回答