如何确定 UITextField 中插入点的位置

发布于 2025-01-03 14:56:20 字数 751 浏览 2 评论 0原文

我有一个 UITextField 子类。

最终,我试图确定文本字段内容中的哪个单词位于插入点下方。

我的具体问题是我是否可以查询 UITextField 的当前插入点。

每当我在字段内移动插入点时,UITextFieldDidChangeNotification 就会触发,因此正在跟踪某些内容。但我在文本字段实例中找不到任何可查询的内容来告诉我插入点现在所在的位置。

能够请求从可见文本开头的字符偏移量将会是很好的。

这在 iOS 5 中可能吗?我在这里查看了其他相关的问答,一致认为这在 iOS 4 或更早版本中是不可能的。

我已经摆弄了 UITextInput 协议并设法获得了一些看起来相关的数据:

UITextRange *selectedTextRange = [super selectedTextRange];
UITextPosition *start = [selectedTextRange start];
UITextPosition *end = [selectedTextRange end];
NSLog (@"selectionRange: %@; start: %@; end: %@", 
        selectedTextRange, start, end);

有没有办法将 UITextPosition 转换为相关的 NSRange 或某种字符偏移量,让我知道插入点是?

任何帮助将不胜感激。

I have a UITextField subclass.

Ultimately, I'm trying to determine which word in the text field's content is under the insertion point.

My specific question is whether I can query a UITextField for the current insertion point.

UITextFieldDidChangeNotification fires whenever I move the insertion point within the field, so something is being tracked. But I can't find anything to query in the text field instance to tell me where the insertion point is now located.

Being able to ask for a character offset from the beginning of the visible text would be swell.

Is this possible in iOS 5? I've looked through other related Q&A here and the consensus seems to be that it wasn't possible in iOS 4 or earlier.

I've diddled around with the UITextInput protocol and managed to get some data that looks relevant:

UITextRange *selectedTextRange = [super selectedTextRange];
UITextPosition *start = [selectedTextRange start];
UITextPosition *end = [selectedTextRange end];
NSLog (@"selectionRange: %@; start: %@; end: %@", 
        selectedTextRange, start, end);

Is there a way to turn a UITextPosition into a relevant NSRange or some kind of character offset to let me know where the insertion point is?

Any help would be much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文