NSOpenPanel作为表格

时间:2015-04-13 00:45:11

标签: swift nsopenpanel

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

我有一个viewController类,它包含一个按钮的IBAction。此按钮应该从该viewController:

打开NSOpenPanel作为工作表
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(..),它适用于上面的行,但这不是工作表效果

2 个答案:

答案 0 :(得分:12)

您需要从窗口上的面板中调用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")
    }
})

答案 1 :(得分:1)

快捷键5

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