Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Identify word before cursor in textView (with special Characters)

I have an extension which identify and return the word before the cursor:

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
}

I am using UItextGranularity.word and works fine.

However my issue is this:

If at the beginning of the word i have an @ it won't be returned. so if i have @jon the currentword will be jon. Is there a way to include the @ so to have the complete word with the special Character?

Thank you

like image 243
Marco Avatar asked Nov 16 '17 14:11

Marco


Video Answer


1 Answers

It doesn't seem like you can do it with UITextInputTokenizer. You can try this solution:

var currentWord: String? {
    let regex = try! NSRegularExpression(pattern: "\\S+$")
    let textRange = NSRange(location: 0, length: selectedRange.location)
    if let range = regex.firstMatch(in: text, range: textRange)?.range {
        return String(text[Range(range, in: text)!])
    }
    return nil
}
like image 105
Guy Kogus Avatar answered Oct 15 '22 17:10

Guy Kogus