Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the cursor position of UITextField in ios

I am trying to control the cursor position in the UITextField. Users cannot insert more than one character at a time into the middle of the text field. It moves it to the end of the textfield. So this post in SO: Control cursor position in UITextField It solves my problem. But I need to know the current cursor position.

My code looks like this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if (textField.tag == 201) 
   {
     [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)];
   }
}

It is giving me an error at idx. How do I find that?

like image 389
lakshmen Avatar asked May 08 '13 03:05

lakshmen


2 Answers

UITextField conforms to the UITextInput protocol which has methods for getting the current selection. But the methods are complicated. You need something like this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 201) {
        UITextRange *selRange = textField.selectedTextRange;
        UITextPosition *selStartPos = selRange.start;
        NSInteger idx = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selStartPos];

        [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)];
    }
}
like image 197
rmaddy Avatar answered Oct 23 '22 12:10

rmaddy


Swift version

if let selectedRange = textField.selectedTextRange {

    let cursorPosition = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: selectedRange.start)
    print("\(cursorPosition)")
}

My full answer about getting and setting the cursor position is here.

like image 22
Suragch Avatar answered Oct 23 '22 11:10

Suragch