'NSOpenPanel Method on ViewModel don't display the return value on the View
I am quite new in development but I am progressing! My idea is to open a database (via NSOpenPanel) and then access the data using different methods.
Below is the model (Model), the ViewModel (and the NSOpenPanel method) as well as the View.
import Foundation
// DataBase Model
struct Database {
var path: [URL?]
var firstRecord: Date
var lastRecord: Date
}
import AppKit
import SwiftUI
// ViewModel
class DatabaseFileSelectedViewModel: ObservableObject {
@Published public var path: [Database] = []
init() {
self.path = path
}
// select the file and open the database, sort it by localTime...
func fileSelected() -> [URL?] {
var path: [URL?] = [URL?]()
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = true
openPanel.allowsMultipleSelection = false
let response = openPanel.runModal()
if response == .OK { path = openPanel.urls }
return path
}
}
import SwiftUI
// VIEW
struct FileSelectedView: View {
@StateObject var DatabaseFileSelectedVM = DatabaseFileSelectedViewModel()
// Body
var body: some View {
HStack (content: {
VStack (alignment: .leading, content: {
Button(action: {
let pathSelected = DatabaseFileSelectedVM.fileSelected()
}, label: { Label("Select File…", systemImage: "doc")})
Divider()
Text("The File selected is: ")
Text(pathSelected) // ERROR!
})
.font(.headline)
.padding([.top, .leading], 10)
Spacer()
})
Spacer()
}
}
My question: The fileSelected() method does return an array of type [URL?], however I don't know how to structure my View so that it incorporates the selected path when validating the file selection window. Also, the compiler tells me Cannot find 'pathSelected' in scope. How to structure my View?
Thank you very much for any thoughts you can give me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
