Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change cursor in UITextField when set new text

I discovery one thing. If i set yes to function

- textField:shouldChangeCharactersInRange:replacementString:

The cursor stay in the same place I type, like ("|" = cursor)

"|"     => Empty , type a
"a|"    => type b
"ab|"   => change cursor
"a|b"   => type c
"ac|b"  => type d
"acd|b" => change cursor
"ac|db" => type backspace
"a|db"  => type backspace again
"|db"   => *result*

But, if I have to change the text, like put a "-" in penultimate character, I do the logic thing and set the text with:

  [textField setText:newText];

But the sample above will be in this way:

"|"      => Empty , type a
"a|"     => type b               (put character "-" automatic)
"a-b|"   => user change cursor
"a|-b"   => type c    
"ac-b|"  => type d               ## the cursor is in end ##
"acb-d|" => change cursor        ## "d" is in wrong place, the user have to  
                                 ## change cursor to reproduce the result above
"ac|b-d" => type backspace
"ab-d|"  => type backspace again   ## the cursor is in end again ##
"a-b|"   => *result*               ## I want delete "a" but it delete "d"

How can I set the cursor to the result is the same "|d-b" like in the first sample? Or better question: How change the text and the cursor in a UITextField?

like image 430
Rodrigo Avatar asked Nov 04 '22 15:11

Rodrigo


1 Answers

I found the solution. I can't choice the cursor place, but it do what I want. You have to use the function of protocol UIKeyInput There are 2 good function:

- (void)insertText:(NSString *)text;
- (void)deleteBackward;

Than, redoing my test case, I have:

"|"      => Empty , type a
"a|"     => type b               (put character "-" automatic)
"a-b|"   => user change cursor
"a|-b"   => type c               (enter the character with a [textField insertText:@"c"]
"ac|-b"  => type d               (the same thing: [textField insertText:@"d"])
"acd|-b" => change cursor
"ac|d-b" => type backspace       (use a [textField deleteBackward])
"a|d-b"  => type backspace
"|d-b"   => *result*             (Work!!!)

You can't change the cursor, but for normal typing it solve the problems!.

like image 105
Rodrigo Avatar answered Nov 13 '22 04:11

Rodrigo