0
votes

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
}
1
"Observing" Text doesn't really make sense because it doesn't have a changing value. You already have access to what's in the Text via vehicle.name. Are you just asking how to call a function on the view model? - jnpdx
Yep, but I want it in the View Model. Data for the vehicle.name comes from another view. - beginner992
The two paths are generally: 1) Use onAppear in the view to send a value to the view model and load data 2) Use init on the view so that you can explicitly send an initial value to the view model (not really recommended, since init shouldn't do heavy work) - jnpdx
Can you show me any example? I mean onAppear. - beginner992
I added an answer with a simple example. I couldn't use your types since they're not included here and it wasn't clear where the vehicle.name would be going, but it should be enough to get you started. - jnpdx

1 Answers

1
votes

As discussed in the comments, here's an example of using onAppear to pass a value to an ObservableObject:

class ViewModel : ObservableObject {
    @Published var myValue = ""
}

struct ContentView : View {
    private var myValue = "Updated value"
    @ObservedObject private var viewModel = ViewModel()
    
    var body: some View {
        Text(viewModel.myValue)
            .onAppear {
                viewModel.myValue = myValue
            }
    }
}