The example code below shows what I am trying to achieve: When the user types a '*', it should be replaced with a '×'.
It looks like it works, but the cursor position is corrupted, even though it looks OK, and the diagnostics that is printed below shows a valid index. If you type "12*34" you get "12×43" because the cursor is inserting before the shown cursor instead of after.
How can I fix this?
struct ContentView: View {
@State private var input: String = ""
@State private var selection: TextSelection? = nil
var body: some View {
VStack {
TextField("Type 12*34", text: $input, selection: $selection)
.onKeyPress(action: {keyPress in
handleKeyPress(keyPress)
})
Text("Selection: \(selectionAsString())")
}.padding()
}
func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result {
if (keyPress.key.character == "*") {
insertAtCursor(text: "×")
moveCursor(offset: 1)
return KeyPress.Result.handled
}
return KeyPress.Result.ignored
}
func moveCursor(offset: Int) {
guard let selection else { return }
if case let .selection(range) = selection.indices {
print("Moving cursor from \(range.lowerBound)")
let newIndex = input.index(range.lowerBound, offsetBy: offset, limitedBy: input.endIndex)!
let newSelection : TextSelection.Indices = .selection(newIndex..<newIndex)
if case let .selection(range) = newSelection {
print("Moved to \(range.lowerBound)")
}
self.selection!.indices = newSelection
}
}
func insertAtCursor(text: String) {
guard let selection else { return }
if case let .selection(range) = selection.indices {
input.insert(contentsOf: text, at: range.lowerBound)
}
}
func selectionAsString() -> String {
guard let selection else { return "None" }
switch selection.indices {
case .selection(let range):
if (range.lowerBound == range.upperBound) {
return ("No selection, cursor at \(range.lowerBound)")
}
let lower = range.lowerBound.utf16Offset(in: input)
let upper = range.upperBound.utf16Offset(in: input)
return "\(lower) - \(upper)"
case .multiSelection(let rangeSet):
return "Multi selection \(rangeSet)"
@unknown default:
fatalError("Unknown selection")
}
}
}