Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...