UITextField获取当前编辑的单词 [英] UITextField get currently edited word
问题描述
我正在开发一个自动完成组件,我有一个问题需要以一种简单的方式解决。
I'm working on an autocompletion component and I have one problem that I would like to solve in some easy way.
我想支持对自动填充文本进行编辑,例如:
I want to support edits to autocompleted text, for example:
blablabl @usertag blablabl
如果用户返回并编辑@usertag字符串,我想在编辑时启动自动完成功能。
If user goes back and edits @usertag string, I would like to start autocompletion when it's edited.
问题是,如何从textfield获取当前编辑的单词。我考虑过采用光标位置,将nsstring分隔为单词(空格)并计算从第一个单词到光标位置的字母。
Question is, how to get currently edited word from textfield. I thought about taking cursor position, seperate nsstring to word by " " (space) and count letters from first word to cursor position.
有没有更简单的方法可以做到这一点?
Is there any easier way for doing that?
推荐答案
好的,我找到了一种方便的方法。也许有人会发现它很有用:
Ok I found a way to do it quite easily. Maybe someone will find it useful:
UITextRange* selectedRange = [textField selectedTextRange];
NSInteger cursorOffset = [textField offsetFromPosition:0 toPosition:selectedRange.start];
NSString* text = textField.text;
NSString* substring = [text substringToIndex:cursorOffset];
NSString* editedWord = [[substring componentsSeparatedByString:@" "] lastObject];
这篇关于UITextField获取当前编辑的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!