I have a problem. I am passing a string between views and use it, to the download data from the database. Then the string goes to the Text. I want to observe Text (not TextField) or pass String to the ViewModel in SwiftUI. I know how to do it in Textfield case, but there is possible in the Text?
View:
import SwiftUI
struct RefuelingListView: View {
@ObservedObject var viewModel: RefuelingListViewModel
var vehicle: Vehicle
var body: some View {
VStack(alignment: .leading) {
Text(vehicle.name)
.font(.system(size: 24))
.bold()
.frame(width: 380, height: 60, alignment: .topLeading)
.padding(.top, -20)
.padding(.leading, 10)
List(viewModel.refuelings) { refueling in
RefuelingListRow(refueling: refueling)
}
}
}
}
ViewModel:
import Foundation
class RefuelingListViewModel: ObservableObject {
@Published var refuelings = [Refueling]()
private let persistenceService: PersistenceServiceProtocol
init(persistenceService: PersistenceServiceProtocol) {
self.persistenceService = persistenceService
}
Text
doesn't really make sense because it doesn't have a changing value. You already have access to what's in theText
viavehicle.name
. Are you just asking how to call a function on the view model? - jnpdxonAppear
in the view to send a value to the view model and load data 2) Useinit
on the view so that you can explicitly send an initial value to the view model (not really recommended, sinceinit
shouldn't do heavy work) - jnpdxvehicle.name
would be going, but it should be enough to get you started. - jnpdx