12

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

4

3 回答 3

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];
}];
于 2011-12-27T18:07:34.877 回答
27

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

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

if ([openPanel runModal] == NSOKButton)
{
    NSString *selectedFileName = [openPanel filename];
}
于 2011-10-08T00:01:25.587 回答
4

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

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

斯威夫特 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
        }
    }
}
于 2017-06-30T21:02:17.857 回答