Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Created June 28, 2022 16:03
Show Gist options
  • Save mbrandonw/b4bdb52e7a71cde0d7024573d39e199c to your computer and use it in GitHub Desktop.
Save mbrandonw/b4bdb52e7a71cde0d7024573d39e199c to your computer and use it in GitHub Desktop.
FB10492871: TextField writes to binding twice

TextField writes to binding twice

FB10492871

The binding provided to a TextField is written to twice for each keystroke.

Run the following code in a SwiftUI application and type into the text field to reproduce:

import SwiftUI

struct ContentView: View {
  @State var text = ""
  var body: some View {
    TextField(
      "Type something here",
      text: .init(
        get: { self.text },
        set: {
          self.text = $0
          print("Binding set to \($0)")
        }
      )
    )
  }
}

If you apply a text field style other than .automatic it fixes the problem.

This can cause subtle bugs in applications that are hard to catch, such as if you want to track an analytics event anytime a text field is changed. You would knowningly double track all events.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment