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.
Cyrus1
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];
来源:https://stackoverflow.com/questions/10578162/custom-keyboard-set-cursor-position