Created
August 1, 2025 06:19
-
-
Save GeorgeElsham/eaec66aca10c3ef646ce28a21217052b to your computer and use it in GitHub Desktop.
SwiftUI TextField which is perfectly in sync with the text binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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