[英]Get the edited UITextView word
I'm trying to get the word that's being typed from a UITextView
. 我试图从
UITextView
获取正在键入的单词。 I have the following code placed in textViewDidChange(_:)
that I found from another answer on here, but it doesn't work for emojis: 我在下面的另一个答案中找到的
textViewDidChange(_:)
中放置了以下代码,但不适用于表情符号:
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!
}
I've indicated the position that it crashes at in the while loop, and the crash says that "The index X is invalid". 我已经指出了它在while循环中崩溃的位置,并且崩溃表明“索引X无效”。 How can I fix this?
我怎样才能解决这个问题?
You should fetch the last word from the string. 您应该从字符串中获取最后一个单词。 Here is the code to fetch it:
这是获取它的代码:
__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;
}];
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.