I want to get the currently typed word in a UITextView. A way to get a completely typed word can be found here UITEXTVIEW: Get the recent word typed in uitextvi
You can simply extend UITextView and use following method which returns the word around the current location of cursor:
extension UITextView {
func editedWord() -> String {
let cursorPosition = selectedRange.location
let separationCharacters = NSCharacterSet(charactersInString: " ")
// Count how many actual characters there are before the cursor.
// Emojis/special characters can each increase selectedRange.location
// by 2 instead of 1
var unitCount = 0
var characters = 0
while unitCount < cursorPosition {
let char = text.startIndex.advancedBy(characters)
let int = text.rangeOfComposedCharacterSequenceAtIndex(char)
unitCount = Int(String(int.endIndex))!
characters += 1
}
let beginRange = Range(start: text.startIndex.advancedBy(0), end: text.startIndex.advancedBy(characters))
let endRange = Range(start: text.startIndex.advancedBy(characters), end: text.startIndex.advancedBy(text.characters.count))
let beginPhrase = text.substringWithRange(beginRange)
let endPhrase = text.substringWithRange(endRange)
let beginWords = beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
let endWords = endPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
return beginWords.last! + endWords.first!
}
}