2016-09-25 72 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