UITextField获取当前编辑的单词

时间:2014-03-19 13:45:47

标签: ios nsstring uitextfield

我正在处理自动完成组件,我有一个问题需要以一种简单的方式解决。

我想支持对自动填充文字的修改,例如:

 blablabl @usertag blablabl

如果用户返回并编辑@usertag字符串,我想在编辑时启动自动完成功能。

问题是,如何从文本字段中获取当前编辑的单词。我考虑过采取光标位置,将nsstring分隔为#34; " (空格)并计算从第一个单词到光标位置的字母。

有没有更简单的方法呢?

4 个答案:

答案 0 :(得分:8)

好的,我找到了一种很容易做到的方法。也许有人会发现它很有用:

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

答案 1 :(得分:2)

迅速4 解决方案

   func getCurrentEditingWord() ->String? {
        let selectedRange: UITextRange? = self.textView.selectedTextRange
        var cursorOffset: Int? = nil
        if let aStart = selectedRange?.start {
            cursorOffset = self.textView.offset(from: self.textView.beginningOfDocument, to: aStart)
        }
        let text = self.textView.text
        let substring = (text as NSString?)?.substring(to: cursorOffset!)
        let editedWord = substring?.components(separatedBy: " ").last
        return editedWord
    }

答案 2 :(得分:1)

这里是效率高的书呆子的解决方案。用 Swift 4.2 编写。我声称这样做更有效,因为其他答案正在调用String方法String.component,该方法不必要地将整个子字符串转换为数组。同样,这些解决方案总是在光标之前抓住单词,而不一定是当前单词。

extension UITextView {
    /// Returns the current word that the cursor is at.
    func currentWord() -> String {
        guard let cursorRange = self.selectedTextRange else { return "" }
        func getRange(from position: UITextPosition, offset: Int) -> UITextRange? {
            guard let newPosition = self.position(from: position, offset: offset) else { return nil }
            return self.textRange(from: newPosition, to: position)
        }

        var wordStartPosition: UITextPosition = self.beginningOfDocument
        var wordEndPosition: UITextPosition = self.endOfDocument

        var position = cursorRange.start

        while let range = getRange(from: position, offset: -1), let text = self.text(in: range) {
            if text == " " || text == "\n" {
                wordStartPosition = range.end
                break
            }
            position = range.start
        }

        position = cursorRange.start

        while let range = getRange(from: position, offset: 1), let text = self.text(in: range) {
            if text == " " || text == "\n" {
                wordEndPosition = range.start
                break
            }
            position = range.end
        }

        guard let wordRange = self.textRange(from: wordStartPosition, to: wordEndPosition) else { return "" }

        return self.text(in: wordRange) ?? ""
    }
}

答案 3 :(得分:0)

您是否尝试过使用UITextFieldDelegate可用的方法?如果您在编辑单词时访问该单词是您想要的,您可以简单地使用-textField:shouldChangeCharactersInRange:replacementString:在此方法中,您可以访问输入的字符串,并且您还可以在此处为每个新字符执行任何字符串操作输入