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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With