我找到了很多關于如何讓用戶選擇選單項然后打開檔案夾的資源。以下是我所擁有的。
import SwiftUI
@main
struct Oh_My_App: App {
var body: some Scene {
WindowGroup {
ContentView()
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
Button {
if let url = showFileOpenPanel() {
print(url.path)
}
} label: {
Text("Open file...")
}
.keyboardShortcut("O")
}
}
}
func showFileOpenPanel() -> URL? {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = false
openPanel.title = "Selecting a folder..."
openPanel.message = "Please select a folder containing one or more files."
let response = openPanel.runModal()
return response == .OK ? openPanel.url : nil
}
}
好的。那沒問題。我可以列印檔案路徑。好吧,我的實際問題是如何將此值回傳到ContentView?這是ContentView虛擬地運行在此示例應用程式展示。所以我使用ObservableObject如下。
import SwiftUI
@main
struct Oh_My_App: App {
@StateObject var menuObservable = MenuObservable()
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}.commands {
CommandGroup(after: .newItem) {
Button {
menuObservable.openFile()
} label: {
Text("Open file...")
}
.keyboardShortcut("O")
}
}
}
}
class MenuObservable: ObservableObject {
@Published var fileURL: URL = URL(fileURLWithPath: "")
func openFile() {
if let openURL = showFileOpenPanel() {
fileURL = openURL
}
}
func showFileOpenPanel() -> URL? {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = false
openPanel.title = "Selecting a folder..."
openPanel.message = "Please select a folder containing one or more files."
let response = openPanel.runModal()
return response == .OK ? openPanel.url : nil
}
}
// ContentView.swift //
import SwiftUI
struct ContentView: View {
@ObservedObject var menuObservable = MenuObservable()
@State var filePath: String = ""
var body: some View {
ZStack {
VStack {
Text("Hello: \(filePath)")
}.onChange(of: menuObservable.fileURL) { newValue in
filePath = newValue.path
}
}
}
}
我的ContentView不會更新。那么我如何ContentView從選單呼叫中接收一個值App呢?謝謝。
uj5u.com熱心網友回復:
現在,你要創建一個新的實體中MenuObservable的ContentView,所以它并沒有給收到選單命令實體的任何連接。您需要傳遞對現有實體的參考(即由 擁有的實體Oh_My_App)。
在您的 中ContentView,更改@ObservedObject var menuObservable = MenuObservable()為:
@ObservedObject var menuObservable : MenuObservable
在你的Oh_My_App:
WindowGroup {
ContentView(menuObservable: menuObservable)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405642.html
標籤:
