设置新文本时更改UITextField中的光标 [英] Change cursor in UITextField when set new text

查看:53
本文介绍了设置新文本时更改UITextField中的光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一件事.如果我将功能设置为是

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"

如何将光标设置为与第一个示例中的结果相同的"|d-b"?或更好的问题:如何更改UITextField中的文本和光标?

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?

推荐答案

我找到了解决方案.我不能选择光标的位置,但是它可以做我想要的.您必须使用协议 UIKeyInput 的功能.有两个不错的功能:

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

这篇关于设置新文本时更改UITextField中的光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆