Custom Keyboard Set Cursor Position

2020-07-27 05:45发布

问题:

I have a text field tapping on which a custom keyboard appears containing numbers 0-9 and a backspace button. I'm able to delete text at the end as well as from middle of string. But when i delete text from somewhere middle, the cursor jumps to end position. I want cursor to remain at same position where it was while deleting text. Please reply ASAP and thanks in advance.

回答1:

First get the initial position of the cursor (or the end of the selected range):

UITextRange *selectedRange = [textField selectedTextRange];
NSInteger offset = [textField offsetFromPosition:textField.endOfDocument toPosition:selectedRange.end];

After modifying the textField's text, reset the cursor position by using UITextPosition as follows:

UITextPosition *newPos = [textField positionFromPosition:textField.endOfDocument offset:offset];
textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];