自定义键盘设置光标位置 [英] Custom Keyboard Set Cursor Position

查看:455
本文介绍了自定义键盘设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段点击,其中显示包含数字0-9和退格按钮的自定义键盘。我能够删除文本末尾以及字符串中间的文本。但是当我从中间某处删除文本时,光标会跳到结束位置。我希望光标在删除文本时保持在同一位置。
请尽快回复并提前致谢。

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.

推荐答案

首先获取光标的初始位置(或结束所选范围):

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

修改textField的文本后,使用UITextPosition重置光标位置,如下所示:

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

这篇关于自定义键盘设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆