Prevent caret from changing position on auto complete

This commit is contained in:
Shadowfacts 2020-10-12 19:39:50 -04:00
parent ae272582ac
commit 58c6d508ec
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 11 additions and 0 deletions

View File

@ -70,11 +70,17 @@ struct ComposeContentWarningTextField: UIViewRepresentable {
return
}
let distanceToEnd = textField.offset(from: selectedRange.start, to: textField.endOfDocument)
let selectedRangeStartUTF16 = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
let characterBeforeCursorIndex = text.utf16.index(text.startIndex, offsetBy: selectedRangeStartUTF16)
textField.text!.replaceSubrange(lastWordStartIndex..<characterBeforeCursorIndex, with: string)
didChange(textField)
// keep the cursor at the same position in the text, immediately after what was inserted
let newCursorPosition = textField.position(from: textField.endOfDocument, offset: -distanceToEnd)!
textField.selectedTextRange = textField.textRange(from: newCursorPosition, to: newCursorPosition)
}
private func updateAutocompleteState(textField: UITextField) {

View File

@ -239,10 +239,15 @@ struct MainComposeWrappedTextView: UIViewRepresentable {
return
}
let distanceToEnd = text.utf16.count - textView.selectedRange.upperBound
let characterBeforeCursorIndex = text.utf16.index(text.startIndex, offsetBy: textView.selectedRange.upperBound)
textView.text.replaceSubrange(lastWordStartIndex..<characterBeforeCursorIndex, with: string)
self.textViewDidChange(textView)
// keep the cursor at the same position in the text, immediately after what was inserted
textView.selectedRange = NSRange(location: textView.text.utf16.count - distanceToEnd, length: 0)
}
private func updateAutocompleteState() {