NSOpenPanel - 一切都弃用了吗?

时间:2011-10-07 23:56:42

标签: macos cocoa nsopenpanel

我一直试图让一个窗口显示要求该人选择一个文件,我最终做到了。问题是,Xcode抱怨我正在使用的方法已被弃用。我查看了class reference,但从“运行面板”部分下的所有内容都已弃用,自Mac OS 10.6起。我现在应该使用不同的课吗?

3 个答案:

答案 0 :(得分:30)

在10.6中,这些类有一些变化。其中一个好处是现在有一个基于块的API。

以下是有关如何使用该代码段的代码段:

NSOpenPanel *panel = [[NSOpenPanel openPanel] retain];

// Configure your panel the way you want it
[panel setCanChooseFiles:YES];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:[NSArray arrayWithObject:@"txt"]];

[panel beginWithCompletionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {

        for (NSURL *fileURL in [panel URLs]) {
            // Do what you want with fileURL
            // ...
        }
    }

    [panel release];
}];

答案 1 :(得分:26)

据我所知,您可以使用runModal方法,如下所示:

NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];

if ([openPanel runModal] == NSOKButton)
{
    NSString *selectedFileName = [openPanel filename];
}

答案 2 :(得分:3)

看到我六年后如何发现这个问题有用,而且由于没有快速的答案,这里有一个快捷的解决方案。

您将找到两个样本,一个作为独立窗口,另一个作为工作表。

Swift 3.0

func selectIcon() {
    // create panel
    let panel = NSOpenPanel()

    // configure as desired
    panel.canChooseFiles = true
    panel.canChooseDirectories = false
    panel.allowsMultipleSelection = false
    panel.allowedFileTypes = ["png"]

    // *** ONLY USE ONE OF THE FOLLOWING OPTIONS, NOT BOTH ***

    // ********************** OPTION 1 ***********************
    // use this if you want a selection window to display that is
    // displayed as a separate stand alone window
    panel.begin { [weak self] (result) in
        guard result == NSFileHandlingPanelOKButton, panel.urls.isEmpty == false, let url = panel.urls.first else {
            return
        }

        let image = NSImage.init(contentsOf: url)
        DispatchQueue.main.async {
            self?.iconImageView.image = image
        }
    }

    // ********************** OPTION 2 ***********************        
    // use this if you want a sheet style view that displays sliding
    // down from your apps window
    panel.beginSheetModal(for: self.view.window!) { [weak self] (result) in
        guard result == NSFileHandlingPanelOKButton, panel.urls.isEmpty == false, let url = panel.urls.first else {
            return
        }

        let image = NSImage.init(contentsOf: url)
        DispatchQueue.main.async {
            self?.iconImageView.image = image
        }
    }
}