Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

ios - Get currently typed word in UITextView

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.

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

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

So the functionality I'm after is:

  • 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works for me.

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
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...