SwiftUI
TextField
Live Changes
Swift Programming
iOS Development

How to detect live changes on TextField in SwiftUI?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

SwiftUI makes live TextField updates straightforward through bindings, but production apps often need more than simple state sync. You may need debounced search requests, validation feedback, or side effects triggered only after meaningful changes. Choosing between .onChange, Combine publishers, and view-model bindings determines how cleanly these behaviors scale. This guide shows reliable patterns for detecting text changes in real time while keeping SwiftUI code responsive and maintainable.

Basic Live Change Detection with @State

The simplest pattern uses @State and .onChange.

swift
1import SwiftUI
2
3struct SearchView: View {
4    @State private var query = ""
5
6    var body: some View {
7        TextField("Search", text: $query)
8            .textFieldStyle(.roundedBorder)
9            .onChange(of: query) { newValue in
10                print("live query:", newValue)
11            }
12            .padding()
13    }
14}

This runs on every character change and is ideal for local UI reactions.

Move Logic into ViewModel for Scalability

For non-trivial behavior, bind to @ObservedObject or @StateObject and handle processing in view model.

swift
1final class SearchVM: ObservableObject {
2    @Published var query = ""
3    @Published var validationMessage: String? = nil
4
5    func validate() {
6        validationMessage = query.count < 3 ? "Enter at least 3 characters" : nil
7    }
8}
9
10struct SearchScreen: View {
11    @StateObject private var vm = SearchVM()
12
13    var body: some View {
14        VStack {
15            TextField("Type here", text: $vm.query)
16                .onChange(of: vm.query) { _ in vm.validate() }
17            if let msg = vm.validationMessage {
18                Text(msg).foregroundColor(.red)
19            }
20        }
21        .padding()
22    }
23}

This separates UI rendering from business rules.

Immediate API calls on every keystroke can overload backend and UI. Debounce with Combine.

swift
1import Combine
2
3final class DebouncedSearchVM: ObservableObject {
4    @Published var query = ""
5    private var cancellables = Set<AnyCancellable>()
6
7    init() {
8        $query
9            .removeDuplicates()
10            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
11            .sink { value in
12                print("trigger search for:", value)
13                // call API
14            }
15            .store(in: &cancellables)
16    }
17}

This keeps typing smooth while limiting side-effect frequency.

Input Formatting and Focus Coordination

For formatted fields (phone, currency), sanitize in onChange carefully to avoid recursive updates.

swift
1.onChange(of: amountText) { newValue in
2    let filtered = newValue.filter { $0.isNumber || $0 == "." }
3    if filtered != newValue {
4        amountText = filtered
5    }
6}

If focus flow matters, combine with @FocusState to trigger validation on focus loss vs every keystroke.

Practical Verification Workflow

A strong way to avoid regressions is to validate changes in three stages: baseline, targeted change, and repeatability. First, capture a baseline command/output before applying fixes so you can prove improvement. Second, apply one focused change at a time, then rerun the exact same check to confirm causality. Third, rerun the validation multiple times (or with nearby input variants) to ensure behavior is stable and not a one-off pass.

A simple validation template:

bash
1# 1) capture baseline behavior
2./run_case.sh > before.txt
3
4# 2) apply one targeted fix
5# edit code/config based on this article
6
7# 3) validate after change
8./run_case.sh > after.txt
9diff -u before.txt after.txt

If your stack has tests, add at least one regression test that fails before the fix and passes after it. This turns troubleshooting knowledge into durable protection against future changes. In team environments, including the exact commands used for verification in pull requests or runbooks makes results reproducible across machines and CI.

Operational Checklist for Production Use

Before shipping a fix or optimization, confirm environment parity and observability. Verify toolchain/runtime versions, capture key metrics, and define rollback criteria. A technically correct local fix can still fail in production if infrastructure assumptions differ.

bash
1# Example pre-release checks
2./lint.sh
3./test.sh
4./smoke_test.sh

A minimal release checklist usually includes: compatible dependency versions, representative test coverage, explicit monitoring signals, and a rollback plan. This discipline reduces the chance that a local solution introduces new issues under real traffic or larger datasets.

Common Pitfalls

  • Triggering expensive work on each keystroke without debounce/throttle.
  • Putting heavy business logic directly in the view body instead of a view model.
  • Creating update loops when mutating the same bound value inside onChange.
  • Ignoring duplicate emissions and making redundant network requests.
  • Treating all fields the same when some should validate on submit rather than live.

Summary

Live TextField change detection in SwiftUI starts with bindings and .onChange, then scales through view models and Combine-based debounce. Use direct updates for lightweight UI behavior and controlled pipelines for network or validation side effects. With these patterns, you get responsive input handling without unnecessary complexity or performance regressions.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.