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];