在MacOs的SwiftUI中打开FileDialog [英] Open a FileDialog in SwiftUI on MacOs

查看:45
本文介绍了在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)
  }
}

这篇关于在MacOs的SwiftUI中打开FileDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆