Search code examples
iosswiftuitextfield

TextField not changing foreground color in iOS 17.4


Given the following view:

struct ContentView: View {

    @State private var text: String = ""

    var body: some View {
        VStack {
            TextField("Example", text: self.$text)
            Text(self.text)
        }
        .padding()
        .foregroundStyle(self.text.count % 2 == 0 ? .red : .blue)
    }
}

When typing text, I would expect the foreground color of the TextField to change between red and blue. However, it does not on iOS 17.4 (it does on iOS 16.x and iOS 17 up to 17.2). Is there a new way to achieve this behaviour or is it potentially a bug in iOS 17.3+?


Solution

  • Running on an iPhone 15 simulator with iOS 17.4, the Text was changing color, but the TextField was not. This may be because, the TextField is the source of changes to the state variable text (as text is entered) and this doesn't seem to trigger indirect changes to itself.

    A workaround is to use a separate state variable for the color and update it in an .onChange handler:

    @State private var text: String = ""
    @State private var fgColor = Color.red
    
    var body: some View {
        VStack {
            TextField("Example", text: $text)
            Text(text)
        }
        .padding()
        .foregroundStyle(fgColor)
        .onChange(of: text) { oldVal, newVal in
            fgColor = newVal.count % 2 == 0 ? .red : .blue
        }
    }