Get currently typed word in a UITextView

前端 未结 5 1227
谎友^
谎友^ 2020-12-19 23:19

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

5条回答
  •  醉酒成梦
    2020-12-20 00:04

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

提交回复
热议问题