Fix: Detect Live TextField Changes in SwiftUI with onChange and Custom Bindings

Written by

in

Quick answer: Use the .onChange(of:) modifier on the TextField (iOS 14+) to run code on every keystroke. For iOS 13, create a custom Binding with a setter closure or use .onReceive(text.publisher) with Combine.

Why this happens

SwiftUI’s TextField binds to a @State property, but the binding itself doesn’t expose a “value changed” callback in its basic initializer. The trailing closure in TextField("Placeholder", text: $location) { ... } is actually onCommit — it fires only when the user submits (return key), not on every keystroke. The older onEditingChanged callback only reports focus changes, not content changes.

To react to each character the user types — for autocomplete, validation, or live filtering — you need a mechanism that observes the bound value continuously. SwiftUI 2.0 (iOS 14 / macOS 11) introduced the .onChange(of:) view modifier for exactly this purpose. On earlier versions you must wrap the state in a custom Binding or use Combine’s publisher API.

How to fix it

1. Use .onChange(of:) — iOS 14, macOS 11, watchOS 7, tvOS 14 and later

This is the modern, idiomatic way. Attach the modifier directly to the TextField (or any parent view) and SwiftUI calls your closure with the new value after every update.

import SwiftUI

struct SearchView: View {
    @State private var location: String = ""

    var body: some View {
        VStack {
            Text("Current: \(location)")
            TextField("Search Location", text: $location)
                .onChange(of: location) { newValue in
                    autocomplete(newValue)
                }
                .textFieldStyle(.roundedBorder)
                .padding()
        }
    }

    private func autocomplete(_ query: String) {
        // Perform search, debounce, network call, etc.
        print("Autocomplete for: \(query)")
    }
}

Key points
– The closure receives the new value (newValue in the example).
– Works with any Equatable state, not just String.
– If you need the old value, capture it in a separate @State or use the two-argument form .onChange(of: location) { old, new in ... } (available in later SDKs).

2. Custom Binding with a setter closure — all SwiftUI versions

When you can’t use .onChange, create a computed Binding that writes back to @State and runs your side effect in the setter.

struct SearchView: View {
    @State private var location: String = ""

    private var locationBinding: Binding<String> {
        Binding(
            get: { location },
            set: { newValue in
                location = newValue
                autocomplete(newValue)
            }
        )
    }

    var body: some View {
        VStack {
            Text("Current: \(location)")
            TextField("Search Location", text: locationBinding)
                .textFieldStyle(.roundedBorder)
                .padding()
        }
    }

    private func autocomplete(_ query: String) {
        print("Autocomplete for: \(query)")
    }
}

Why this works
– TextField writes through the binding’s set closure on every keystroke.
– No extra dependencies; works on iOS 13 / SwiftUI 1.0.
– Keep the binding as a computed property (or a let in body) so it always references the current @State.

3. Combine .onReceive with the state’s publisher — iOS 13+

If you prefer a reactive style, @State (and @Binding) expose a publisher property when you import Combine.

import SwiftUI
import Combine

struct SearchView: View {
    @State private var location: String = ""

    var body: some View {
        VStack {
            Text("Current: \(location)")
            TextField("Search Location", text: $location)
                .textFieldStyle(.roundedBorder)
                .padding()
                .onReceive(location.publisher) { newValue in
                    autocomplete(newValue)
                }
        }
    }

    private func autocomplete(_ query: String) {
        print("Autocomplete for: \(query)")
    }
}

Notes
– location.publisher emits the new value after each change.
– Requires import Combine.
– The publisher fires on the main thread, safe for UI updates.

4. Debouncing rapid changes (bonus)

Live callbacks on every keystroke can flood search APIs. Add a debounce operator when using Combine, or use a Task with a delay in .onChange.

// Combine debounce example
.onReceive(location.publisher.debounce(for: .milliseconds(300), scheduler: RunLoop.main)) { query in
    autocomplete(query)
}

// Modern async/await debounce (iOS 15+)
.onChange(of: location) { _, newValue in
    Task {
        try? await Task.sleep(nanoseconds: 300_000_000) // 300 ms
        guard !Task.isCancelled else { return }
        await MainActor.run { autocomplete(newValue) }
    }
}

How to prevent it

  • Prefer .onChange(of:) on supported OS versions — it’s readable and maintained by Apple.
  • Keep side effects (network, DB) out of the binding setter; use the callback to trigger async work instead.
  • Debounce or throttle when the callback does expensive work (search, validation).
  • Avoid retaining self strongly in closures; use [weak self] or capture @State values directly.

FAQ

Does .onChange fire when the value is set programmatically?

Yes. Any mutation of the observed @State property — whether from user input, a button action, or a network response — triggers the closure.

Can I get the previous value in .onChange?

On iOS 17 / macOS 14 and later, use the two-parameter form: .onChange(of: location) { old, new in ... }. On earlier versions, store the previous value in a separate @State variable and update it inside the closure.

Why does my custom binding cause a “Modifying state during view update” warning?

This happens if the setter writes to a different @State property that the view is currently rendering. Ensure the binding’s set only mutates the same property it reads (location in the examples) or defers other mutations with DispatchQueue.main.async.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.