swiftuiviewmodel

TextField not updating until another TextField is updated


I'm encountering an issue with SwiftUI where a TextField does not update immediately when text is entered. Instead, the update only appears after another TextField is updated. I'm using @State variables to manage the text for each TextField.

import SwiftUI

struct ContentView: View {
    @State private var amount = ""
    
    var body: some View {
        VStack{
            TextField("inputNumber", text: $amount)
                .foregroundColor(amount.count < 10 ? .red : .primary)
            
            TextField("inputNumber", text: $amount)
                .foregroundColor(amount.count < 10 ? .red : .primary)
        }
    }

}

the issue


Solution

  • AFAIK, a TextField does not refresh when it is in focus.

    A workaround is to use another var, as shown in the example code.

    struct ContentView: View {
        @State private var amount = ""
        @State private var color = Color.primary // <-- here
        
        var body: some View {
            VStack{
                TextField("inputNumber", text: $amount)
                    .foregroundColor(color) // <-- here
                    .onChange(of: amount) {
                        color = amount.count < 10 ? .red : .primary  // <-- here
                    }
            }
        }
    }