NSOpenPanel in Swift . How to open?

不打扰是莪最后的温柔 提交于 2019-12-03 05:52:19
Seb Jachec
@IBAction func selectAnImageFromFile(sender: AnyObject) {
    let openPanel = NSOpenPanel()
    openPanel.allowsMultipleSelection = false
    openPanel.canChooseDirectories = false
    openPanel.canCreateDirectories = false
    openPanel.canChooseFiles = true
    openPanel.beginWithCompletionHandler { (result) -> Void in
        if result == NSFileHandlingPanelOKButton {
            //Do what you will
            //If there's only one URL, surely 'openPanel.URL'
            //but otherwise a for loop works
        }
    }
}

I'm guessing you got stuck on the completion handler part? In any case, handling the URL from the open panel should be ok from there, but comment if you want me to add more. :)

For Swift 4 the check of the response should be

if response == .OK { 
  ... 
}

Swift 4 version:

let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = false
        openPanel.allowsMultipleSelection = false
        openPanel.canChooseDirectories = false
        openPanel.canCreateDirectories = false
        openPanel.title = "Select a folder"

        openPanel.beginSheetModal(for:self.view.window!) { (response) in
            if response.rawValue == NSFileHandlingPanelOKButton {
                let selectedPath = openPanel.url!.path
                // do whatever you what with the file path
            }
            openPanel.close()
        }
ingconti

my two cents for swift 5.0

override func showChooseFileDialog(title: String){
    let openPanel = NSOpenPanel()
    openPanel.canChooseFiles = false
    openPanel.allowsMultipleSelection = false
    openPanel.canChooseDirectories = false
    openPanel.canCreateDirectories = false
    openPanel.title = title

    openPanel.beginSheetModal(for:self.view.window!) { (response) in
        if response == .OK {
            let selectedPath = openPanel.url!.path
            // do whatever you what with the file path
        }
        openPanel.close()
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!