0

I am using an @EnvironmentObject (which is the ViewModel) and I have a demoData() function.

When I press it the data does change but my View is not updated.

How do I get the data to change in the View?

Thank you.

The view information:

import Combine
import SwiftUI

struct MainView: View {
 
    @EnvironmentObject var entry:EntryViewModel

     var body: some View {

         TextField("Beg Value", text: self.$entry.data.beg)
         TextField("Beg Value", text: self.$entry.data.end)

         Button(action: { self.entry.demoData() }) { Text("Demo Data") }

    }
}

ViewModel:

class EntryViewModel: ObservableObject {
 
    @Published  var data:EntryData = EntryData()

    func demoData() {
     
        var x = Int.random(in: 100000..<120000)
        x = Int((Double(x)/100).rounded()*100)
        data.beg = x.withCommas()
    
        x = Int.random(in: 100000..<120000)
       x = Int((Double(x)/100).rounded()*100)
       data.end = x.withCommas()
    
}

Model:

 EntryData:ObservableObject {

    @Published var beg:String = ""
    @Published var end:String = ""

}

1 Answer 1

1

This is because EntryData is a class and if you change its properties it will still be the same object.

This @Published will only fire when you reassign the data property:

@Published var data: EntryData = EntryData()

A possible solution is to use a simple struct instead of an ObservableObject class:

struct EntryData {
    var beg: String = ""
    var end: String = ""
}

When a struct is changed, it's copied and therefore @Published will send objectWillChange.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.