在MacOs的SwiftUI中打开FileDialog
问题描述:
在MacOS上的SwiftUI应用中,我希望允许用户从MacOS文件系统中选择文件.
我尝试使用 AppKits NSOpenPanel
.
In a SwiftUI app on MacOS I want to allow a users to select a file from the MacOS filesystem.
I try to use AppKits NSOpenPanel
.
我曾这样尝试过,但无法创建NSViewControllerRepresentable.
I tried like this, but I'm not able to create the NSViewControllerRepresentable.
struct ContentView: View {
@State var filename = "Filename"
@State var showFileChooser = false
var body: some View {
HStack {
Text(filename)
Button("select File")
{ self.showFileChooser = true
}.sheet(isPresented: $showFileChooser)
{ FileChooser()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct FileChooser : {
func makeNSViewController(context: Context) -> NSOpenPanel {
NSOpenPanel()
}
func updateNSViewControler(_ nsView: NSOpenPanel, context: Context) {
}
}
这是正确的方法吗?
怎么了?
Is this the correct approach?
What's wrong?
答
其实你不需要,因为 NSOpenPanel
是一个窗口,而不是一个视图控制器.
Actually you don't need to, because NSOpenPanel
is a window, not a view controller.
这是可行的方法.经过Xcode 11.7/macOS 10.15.6的测试
Here is possible approach. Tested with Xcode 11.7 / macOS 10.15.6
struct ContentView: View {
@State var filename = "Filename"
@State var showFileChooser = false
var body: some View {
HStack {
Text(filename)
Button("select File")
{
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
if panel.runModal() == .OK {
self.filename = panel.url?.lastPathComponent ?? "<none>"
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}