Change cursor in UITextField when set new text

六眼飞鱼酱① 提交于 2019-12-21 17:11:38

问题


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?


回答1:


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




回答2:


Did you try using the UITextInput protocol for gathering cursor position information?



来源:https://stackoverflow.com/questions/7196032/change-cursor-in-uitextfield-when-set-new-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!