设置新文本时更改UITextField中的光标

我发现一件事。 如果我设置为是function

- textField:shouldChangeCharactersInRange:replacementString: 

光标停留在我键入的相同位置,如(“|”=光标)

 "|" => 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* 

但是,如果我必须改变文本,就像在倒数第二个字符中放一个"-" ,我做逻辑的事情,并设置文本:

  [textField setText:newText]; 

但是上面的例子就是这样的:

 "|" => Empty , type a "a|" => type b (put character "-" automatic) "ab|" => 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|bd" => type backspace "ab-d|" => type backspace again ## the cursor is in end again ## "ab|" => *result* ## I want delete "a" but it delete "d" 

我如何设置游标的结果是相同的"|db"像在第一个样本? 或者更好的问题: 如何更改UITextField中的文本和光标?

我find了解决scheme。 我不能select光标位置,但它做我想要的。 你必须使用协议UIKeyInput的function有两个很好的function:

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

重做我的testing用例,我有:

 "|" => Empty , type a "a|" => type b (put character "-" automatic) "ab|" => 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|db" => type backspace (use a [textField deleteBackward]) "a|db" => type backspace "|db" => *result* (Work!!!) 

你不能改变光标,但对于正常的打字就可以解决问题了!

您是否尝试使用UITextInput协议来收集光标位置信息?