'Select file or directory in SwiftUI in an AppKit App [duplicate]
How can I display a file dialogue in SwiftUI to choose a directory or file.
I think using a NSViewRepresentable to wrap a NSOpenPanel will not work, as it expects a NSView not a NSPanel.
Any alternative ideas, tips or links? Everything I found was about UIKit.
Solution 1:[1]
import SwiftUI
struct FolderSelector: View {
var body: some View {
Button("Choose Folder") {
self.selectFolder()
}
}
func selectFolder() {
let folderChooserPoint = CGPoint(x: 0, y: 0)
let folderChooserSize = CGSize(width: 500, height: 600)
let folderChooserRectangle = CGRect(origin: folderChooserPoint, size: folderChooserSize)
let folderPicker = NSOpenPanel(contentRect: folderChooserRectangle, styleMask: .utilityWindow, backing: .buffered, defer: true)
folderPicker.canChooseDirectories = true
folderPicker.canChooseFiles = true
folderPicker.allowsMultipleSelection = true
folderPicker.canDownloadUbiquitousContents = true
folderPicker.canResolveUbiquitousConflicts = true
folderPicker.begin { response in
if response == .OK {
let pickedFolders = folderPicker.urls
self.selectedFolder.getFileList(at: pickedFolders)
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pylyp Dukhov |