NSOpenPanel - 设置文件类型?

时间:2010-11-27 01:01:11

标签: cocoa

仅查看我将使用的内容,仅允许选择特定文件(目前为图像)

setFileTypesArray返回

  

NSOpenPanel可能无法响应-setFileTypesArray:

然后面板根本没有打开。继承我的代码:

    NSArray  * fileTypes = [NSArray arrayWithObjects:@"png",@"tiff",@"baz",nil];

NSLog(@"Button Pressed");
[textField setStringValue:@"Test"];
int i; // Loop counter.

NSOpenPanel* openDlg = [NSOpenPanel openPanel];

[openDlg setCanChooseFiles:YES];
[openDlg setFileTypesArray:fileTypes];

感谢。

6 个答案:

答案 0 :(得分:27)

[openDlg setAllowedFileTypes:fileTypes];怎么样?

答案 1 :(得分:13)

您正在寻找NSSaveOpenPanel委托的委托方法

-(BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
{
        NSString* ext = [filename pathExtension];
        if (ext == @"" || ext == @"/" || ext == nil || ext == NULL || [ext length] < 1) {
                return TRUE;
        }

        NSLog(@"Ext: '%@'", ext);

        NSEnumerator* tagEnumerator = [[NSArray arrayWithObjects:@"png", @"tiff", @"jpg", @"gif", @"jpeg", nil] objectEnumerator];
        NSString* allowedExt;
        while ((allowedExt = [tagEnumerator nextObject]))
        {
                if ([ext caseInsensitiveCompare:allowedExt] == NSOrderedSame)
                {
                        return TRUE;
                }
        }

        return FALSE;
}

然后,将面板的委托设置为“self”,或者在上面定义此方法的任何位置。

答案 2 :(得分:10)

你可以去看看

[panel setAllowedFileTypes:[NSImage imageTypes]];

或实现委托NSOpenSavePanelDelegate

并实施

- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url {

    NSString * fileExtension = [url pathExtension];
    if (([fileExtension  isEqual: @""]) || ([fileExtension  isEqual: @"/"]) || (fileExtension == nil)) {
        return YES;
    }

    NSSet * allowed = [NSSet setWithArray:@[@"png", @"tiff", @"jpg", @"gif", @"jpeg"]];
    return [allowed containsObject:[fileExtension lowercaseString]];

}

答案 3 :(得分:8)

您要查找的方法是setAllowedFileTypes - 请参阅父类的文档NSSavePanel

答案 4 :(得分:2)

这对我有用:

 NSArray  * fileTypes = [NSArray arrayWithObjects:@"png",@"jpg",@"tiff",nil];

[openDlg setAllowedFileTypes:fileTypes];       

答案 5 :(得分:0)

我为OSX支付的2美分/迅速5 (您可以指定标题,然后转到“图片”文件夹。

override func showChooseImageDialog(title: String){

    let openPanel = NSOpenPanel()
    openPanel.canChooseFiles = false
    openPanel.allowsMultipleSelection = false
    openPanel.canChooseDirectories = false
    openPanel.canCreateDirectories = false
    openPanel.title = title
    openPanel.canChooseDirectories = false
    openPanel.canChooseFiles = true
    openPanel.allowedFileTypes = NSImage.imageTypes

    openPanel.directoryURL = URL(fileURLWithPath: picturesDir() )


    openPanel.beginSheetModal(for:self.view.window!) { (response) in
        if response == .OK {
            let selectedPath = openPanel.url!.path

            // do whatever you what with the file path

        }
        openPanel.close()
    }

}