NSOpenPanel as sheet

久未见 提交于 2020-05-11 05:33:17

问题


Ive looked around at other answers, but nothing seems to be helping my case.

I have a viewController class which contains an IBAction for a button. This button should open a NSOpenPanel as a sheet from that viewController:

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")
    }
}
}

The problem comes from myFileDialog.beginSheetModalForWindow(..) , it works with the line above, but that is not a sheet effect


回答1:


You need to call beginSheetModalForWindow from your panel on your window, and use a completion block:

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")
    }
})



回答2:


Swift 5

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


来源:https://stackoverflow.com/questions/29596360/nsopenpanel-as-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!