在UITextView中获取当前键入的单词 [英] Get currently typed word in UITextView

查看:86
本文介绍了在UITextView中获取当前键入的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个标记窗口,就像在Facebook中键入@一样,它会在您的朋友之间建议标记哪一个。我想在我的应用程序中使用此功能,但我不能为我的生活弄清楚如何获取当前输入的单词以过滤建议。

I'm trying to make a "tagging window" much like the one used in Facebook where you type "@" and it make suggestions among your friends on which one to tag. I'd like this feature in my app, but I can't for the life of me figure out how to get the currently typed word in order to filter suggestions.

我使用 UITextView 我一直在看这篇文章 https:// stackoverflow.com/a/27380612/4148782

I use an UITextView and I've been looking at this post https://stackoverflow.com/a/27380612/4148782

但我将此问题转换为Swift 3,即便如此,评论也表明这并未解决无论如何。

but I have issues translating this to Swift 3, and even so the comments suggests that this isn't solved anyway.

所以我追求的功能是:


  • 用户启动输入 UITextView ,如果单词以@开头,我想提取单词。

  • 我是喜欢用一定的输入替换这个单词。假设用户输入 @abc ,我过滤了一个说明 abcdef 的建议,然后我希望能够替换 @abc 在UITextView中使用 abcdef

  • User starts typing in a UITextView and if the word begins with a "@" I'd like to extract the word.
  • I'd like to replace the word with a certain input as well. Let's say the user types @abc and I filter a suggestion which states "abcdef", then I want to be able to replace the @abc in the UITextView with "abcdef".

请注意,我想要这个词获取键入和最近输入的单词。

Note that I want the word currently getting typed and not the most recent typed word.

推荐答案

这对我有用。

extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
   }
}

这篇关于在UITextView中获取当前键入的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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