NSOpenPanel 作为 sheet

NSOpenPanel as sheet

我查看了其他答案,但似乎没有任何帮助。

我有一个 viewController class,其中包含一个按钮的 IBAction。此按钮应从 viewController:

打开一个 NSOpenPanel 作为 sheet
class ViewController: NSViewController {
@IBAction func folderSelection(sender: AnyObject) {
    var myFiledialog: NSOpenPanel = NSOpenPanel()
    myFiledialog.prompt = "Select path"
    myFiledialog.worksWhenModal = true
    myFiledialog.allowsMultipleSelection = false
    myFiledialog.canChooseDirectories = true
    myFiledialog.canChooseFiles = false
    myFiledialog.resolvesAliases = true

    //myFiledialog.runModal()

    myFiledialog.beginSheetModalForWindow(self.view.window!, completionHandler: nil)


    var chosenpath = myFiledialog.URL
    if (chosenpath!= nil)
    {
        var TheFile = chosenpath!.absoluteString!
        println(TheFile)
        //do something with TheFile
    }
    else
    {
        println("nothing chosen")
    }
}
}

问题来自 myFileDialog.beginSheetModalForWindow(..) ,它适用于上面的行,但这不是 sheet 效果

您需要从 window 的面板调用 beginSheetModalForWindow,并使用完成块:

let myFiledialog = NSOpenPanel()
myFiledialog.prompt = "Select path"
myFiledialog.worksWhenModal = true
myFiledialog.allowsMultipleSelection = false
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
myFiledialog.resolvesAliases = true
myFiledialog.beginSheetModalForWindow(window, completionHandler: { num in
    if num == NSModalResponseOK {
        let path = myFiledialog.URL
        print(path)
    } else {
        print("nothing chosen")
    }
})

Swift 5

let dialog = NSOpenPanel()
dialog.beginSheetModal(for: self.view.window!){ result in
    if result == .OK, let url = dialog.url {
        print("Got", url)
    }
}