Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get character before cursor in Swift

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".

enter image description here

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.

like image 800
Suragch Avatar asked Jan 22 '16 06:01

Suragch


Video Answer


1 Answers

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
}

enter image description here

The result of

if let text = characterBeforeCursor() {
    print(text)
}

is "e", as per your example.

like image 160
Suragch Avatar answered Oct 13 '22 03:10

Suragch