SwiftUI value in text doesn’t change

I don’t understand why the Text Value doesn’t change. if I remove the TextField, the Text value change :/ is there something about combine or SwiftUI I am missing ?

struct ContentView2: View{
    @State private var numTouches: Int = 0
    @State private var num: String = ""
    
    var body: some View {
        VStack{
            Button("Touch me pls"){
                self.numTouches += 1 
            }
            Text("\(numTouches)")
            TextField("Hello enter a number", text: $num)
        }.onReceive(Just(num)) { newValue in
            if newValue == "" {
                self.numTouches = 0
            } else {
                self.numTouches = Int.init(newValue)!
            } 
        }
    }
}

Upvotes: 1

Views: 206

Answers (1)

New Dev
New Dev

Reputation: 49590

What happens is that when a button is touched, it increases numTouches, which causes the view's body to re-render. .onReceive subscribes to the Just publisher that immediately publishes the value num, which is empty "" in the beginning, and that sets numTouches back to 0.

It sounds that you have really just a single variable, which is being updated from two places:

  • via TextField
  • via Button's action

So, keep it as single @State var numTouches: Int:

struct ContentView2: View{
    @State private var numTouches: Int = 0
    
    var body: some View {
        VStack{
            Button("Touch me pls"){
                self.numTouches += 1 
            }
            Text("\(numTouches)")
            TextField("Hello enter a number", 
                      text: $numTouches, formatter: NumberFormatter()))
              // .keyboardType(.numberPad) // uncomment for number pad keyboard
        }
    }
}

Upvotes: 0

Related Questions