I am doing text replacement in a SwiftUI TextField as the user types. This works fine when the cursor is at the end of the input, but fails when the user moves the cursor to the middle and start typing. As soon as a correction is made, the cursor jumps to the end of the string moving the user's cursor away from where they were editing.
Below is a simple example of a view doing text replacement. Is it possible to get the cursor position inside the onChange modifier, and preserve it without custom wrapping a UITextView. I've done that, and it creates other problems.
struct ContentView: View {
@State private var input: String = ""
var body: some View {
VStack {
TextField("", text: $input)
.onChange(of: input) {
input = input.replacingOccurrences(of: "*", with: "×")
input = input.replacingOccurrences(of: "/", with: "÷")
input = input.replacingOccurrences(of: "pi", with: "π")
}
}
.padding()
}
}