Home > Mobile >  swiftui text view does not update when the property of class changes
swiftui text view does not update when the property of class changes

Time:05-31

A ton of similar questions found, but they all have different conditions - none of them seems to apply to my case.

The Text() view does not update with the property of the class, but the bush button prints the correct value. More info in the snippets.

The View:

import SwiftUI

struct ContentView: View {
   @State private var client : Client = Client()

   var body: some View {
      VStack{
         Text(client.message)             // This view remains constant

         ...

         Button( action: {
             print("\(client.message)")  // Prints correct updated value
         }){
             Text("Mess")
         }
      }
   }
}

The Class:

class Client : ObservableObject{
   private var mqtt: CocoaMQTT!
   @Published var message : String = "Empty"

   ...

   func get_message(mess : String){
      self.message = mess
      self.objectWillChange.send()
   }
}

Even objectWillChange.send() does not seem to trigger the change in the view. Any ideas?

CodePudding user response:

For Objects use @StateObject property wrapper and for String, Int, etc use @State property wrapper.

@State: We use this property wrapper when we observe a property that is exists inside our ContentView.

@StateObject: We use this property wrapper when we are observing properties that exists outside of our ContentView like in our Object, we can observe that property changes by firstly conforming that class to ObservableObject Protocol and marking that property as @Published inside our Object.

struct ContentView: View {
   @StateObject private var client : Client = Client()

   var body: some View {
      VStack{
         Text(client.message)             

         Button( action: {
             print("\(client.message)")  
         }){
             Text("Mess")
         }
      }
   }
}

class Client : ObservableObject{
   private var mqtt: CocoaMQTT!
   @Published var message : String = "Empty"

   func get_message(mess : String){
      self.message = mess
   }
}
  • Related