我正试图从UITextView
中获取正在输入的单词。我在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!
}
我已经指出了它在while循环中崩溃的位置,并且崩溃说“索引X无效”。我该如何解决这个问题?
答案 0 :(得分:0)
您应该从字符串中获取最后一个单词。以下是获取它的代码:
currentPage: params.page_number || 1
希望这有帮助!