Custom Keyboard Set Cursor Position

邮差的信 提交于 2019-12-06 13:45:06

问题


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


来源:https://stackoverflow.com/questions/10578162/custom-keyboard-set-cursor-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!