Yesterday I was working on getting and setting the cursor position in a UITextField
. Now I am trying to get the character just before the cursor position. So in the following example, I would want to return an "e".
func characterBeforeCursor() -> String
Notes
I didn't see any other SO questions that were the same of this, but maybe I missed them.
I wrote this question first and when I find an answer I will post both the question and the answer at the same time. Of course, better answers are welcomed.
I said "character" but String
is fine.
If the cursor is showing and the position one place before it is valid, then get that text. Thanks to this answer for some hints.
func characterBeforeCursor() -> String? {
// get the cursor position
if let cursorRange = textField.selectedTextRange {
// get the position one character before the cursor start position
if let newPosition = textField.position(from: cursorRange.start, offset: -1) {
let range = textField.textRange(from: newPosition, to: cursorRange.start)
return textField.text(in: range!)
}
}
return nil
}
The result of
if let text = characterBeforeCursor() {
print(text)
}
is "e", as per your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With