swift - 在 MacO 上的 SwiftUI 中打开 FileDialog

标签 swift macos swiftui

在 MacOS 上的 SwiftUI 应用程序中,我希望允许用户从 MacOS 文件系统中选择一个文件。
我尝试使用 AppKits NSOpenPanel
我试过这样,但我无法创建 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) {
  }
}
这是正确的方法吗?
怎么了?

最佳答案

其实你不需要,因为 NSOpenPanel 是一个窗口,而不是一个 View Controller 。
这是可能的方法。使用 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)
  }
}

关于swift - 在 MacO 上的 SwiftUI 中打开 FileDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63764637/

相关文章:

ios - 3D Touch 快速操作根本不起作用

ruby - 安装 pg gem 时遇到问题

macos - Mac OS X 是否带有内置于 Emacs 的 Lisp 环境?

cocoa - Core Data 中线程安全的唯一实体实例

button - 如何获取按钮发件人 ID?在 SwiftUI 中

arrays - 在 Swift 中修改数组项

ios - 如何根据操作系统版本创建实例变量

swift - 在 SwiftUI 类中调用包装的 UIViewController 函数时获取 nil

ios - WKWebView 在 iOS 11 之前导致语法错误

iOS SwiftUi : NavigationView inside a ZStack