【发布时间】:2011-10-07 23:56:42
【问题描述】:
我一直试图让一个窗口出现,让人们选择一个文件,我最终做到了。问题是,Xcode 抱怨我使用的方法已被弃用。我查看了class reference,但从 Mac OS 10.6 开始,“运行面板”部分下的所有内容都已被弃用。我现在应该使用不同的课程吗?
【问题讨论】:
标签: macos cocoa nsopenpanel
我一直试图让一个窗口出现,让人们选择一个文件,我最终做到了。问题是,Xcode 抱怨我使用的方法已被弃用。我查看了class reference,但从 Mac OS 10.6 开始,“运行面板”部分下的所有内容都已被弃用。我现在应该使用不同的课程吗?
【问题讨论】:
标签: macos cocoa nsopenpanel
在 10.6 中,对此类进行了一些更改。好处之一是现在有了基于块的 API。
这是一个关于如何使用它的代码 sn-p:
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];
}];
【讨论】:
据我所知,您可以使用如下所示的runModal 方法:
NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
if ([openPanel runModal] == NSOKButton)
{
NSString *selectedFileName = [openPanel filename];
}
【讨论】:
NSSavePanel 实现的,它是NSOpenPanel 的超类。 +1
filename 告诉我 [openPanel filename] 从 10.6 开始已被弃用。替换为[openPanel URLs](在纪尧姆的回答中使用)。
六年后我发现这个问题很有用,由于没有快速的答案,这里有一个快速的解决方案。
您会找到两个示例,一个作为独立窗口,另一个作为工作表。
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
}
}
}
【讨论】:
.begin 是一个完成处理程序。对于未来的围观者:你也可以这样做:let response = panel.runModal();if response == NSApplication.ModalResponse.OK {/*do things with panel.url*/}也适用于.CANCEL