6

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.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

3 Answers3

16

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.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
0

You can also use this:

NSInteger endOffset = [textfld offsetFromPosition:textfld.beginningOfDocument toPosition:range1.end];

NSRange offsetRange = NSMakeRange(endOffset-1, 1);

NSString *str1 = [textfld.text substringWithRange:offsetRange];
NSLog(@"str1= %@",str1);
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Reshmi Majumder
  • 961
  • 4
  • 15
0

In swift you can use

let range1 : UITextRange = textField.selectedTextRange!

let  endoffset : NSInteger = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: range1.end)

let offsetRange : NSRange = NSMakeRange(endoffset-1, 1)

let index: String.Index = (textField.text?.startIndex.advancedBy(offsetRange.location))!

let str1 : String = (textField.text?.substringFromIndex(index))!

let index1 : String.Index = str1.startIndex.advancedBy(1)

let str2: String = str1.substringToIndex(index1)

print(str2)
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Reshmi Majumder
  • 961
  • 4
  • 15
  • 2
    This will work in some situations but crashes in other situations. For example, try entering a string of emoji and see what the result is. (By the way, you can format your code by indenting every line 4 spaces.) – Suragch Jan 22 '16 at 10:03