Skip to content

Instantly share code, notes, and snippets.

@GeorgeElsham
Created August 1, 2025 06:19
Show Gist options
  • Save GeorgeElsham/eaec66aca10c3ef646ce28a21217052b to your computer and use it in GitHub Desktop.
Save GeorgeElsham/eaec66aca10c3ef646ce28a21217052b to your computer and use it in GitHub Desktop.
SwiftUI TextField which is perfectly in sync with the text binding
import SwiftUI
struct RigidTextField: View {
@Binding private var externalText: String
@State private var internalText: String
private let title: String
init(_ title: String, text: Binding<String>) {
self.title = title
_externalText = text
internalText = text.wrappedValue
}
var body: some View {
TextField(title, text: $internalText)
.onChange(of: internalText) {
guard internalText != externalText else {
return
}
// This works, don't change it!
externalText = internalText
internalText = externalText
}
.onChange(of: externalText) {
guard internalText != externalText else {
return
}
internalText = externalText
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment