![](/img/trans.png)
[英]How to programmatically open the app window from the background in SwiftUI on macOS (not iOS)?
[英]Open a FileDialog in SwiftUI on MacOs
在 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
是一個窗口,而不是一個視圖控制器。
這是可能的方法。 使用 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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.