Skip to content

Instantly share code, notes, and snippets.

@ra9r
Created October 8, 2022 01:08
Show Gist options
  • Save ra9r/d017bc1e5808d6d53e43a340982f8afb to your computer and use it in GitHub Desktop.
Save ra9r/d017bc1e5808d6d53e43a340982f8afb to your computer and use it in GitHub Desktop.
Examples of reacting to changes in TextFields
struct ContentView : View {
@State var text1 = ""
@State var text2 = ""
@StateObject var model = ViewModel()
var body: some View {
TextField("Text 1", text: $text1)
{ editing in
print("Editing?: \(editing)")
} onCommit: {
print("Committed")
}
TextField("Text 2", text: $text2)
.onChange(of: text2) { (vewValue) in
print(newValue)
}
TextField("Text 3", text: $model.text3)
}
final class ViewModel: ObservableObject {
@Published var text3 = ""
init() {
$text3.sink { newValue in
print(newValue)
}
}
}
}
@ra9r
Copy link
Author

ra9r commented Oct 8, 2022

Example was originally provided in a video by Flo writes Code (https://www.youtube.com/watch?v=EMLcwW5RJss)

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