2016-09-25 49 views
0

我试图从UITextView中输入正在输入的单词。我放在textViewDidChange(_:),我从这里另一个答案找到了下面的代码,但它并不适用于表情符号,工作:获取已编辑的UITextView单词

func editedWord() -> String { 
    let cursorPosition = selectedRange.location 
    let separationCharacters = CharacterSet(charactersIn: " ") 

    // 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.index(text.startIndex, offsetBy: characters) 
     let int = text.rangeOfComposedCharacterSequence(at: char) // Crashes here when there's an emoji. 
     unitCount = text.distance(from: text.startIndex, to: int.upperBound) 
     characters += 1 
    } 

    let beginRange = Range(uncheckedBounds: (lower: text.index(text.startIndex, offsetBy: 0), upper: text.index(text.startIndex, offsetBy: characters))) 
    let endRange = Range(uncheckedBounds: (lower: text.index(text.startIndex, offsetBy: characters), upper: text.index(text.startIndex, offsetBy: text.characters.count))) 


    let beginPhrase = text.substring(with: beginRange) 
    let endPhrase = text.substring(with: endRange) 

    let beginWords = beginPhrase.components(separatedBy: separationCharacters) 
    let endWords = endPhrase.components(separatedBy: separationCharacters) 

    return beginWords.last! + endWords.first! 
} 

我已经表明,它崩溃在while循环的位置,崩溃说“索引X是无效的”。我怎样才能解决这个问题?

回答

0

您应该从字符串中提取最后一个单词。这里是取回它的代码:

__block NSString *lastWord = nil; 

[someNSStringHere enumerateSubstringsInRange:NSMakeRange(0, [someNSStringHere length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) { 

    lastWord = substring; 
    *stop = YES; 
}]; 

希望这有助于!

+0

OP正在使用Swift。你应该使用Swift代码来回答。 –

+0

这不适用于表情符号,只会显示输入的最后一个单词。我也希望它是光标当前所在的单词。而且,很快。 – Tometoyou