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!
}
내가는 동안 루프에서 충돌하는 위치를 표시 한하고, 충돌은 "색인 X가 유효하지 않습니다"라고 말합니다. 이 문제를 어떻게 해결할 수 있습니까?
OP는 스위프트를 사용합니다. Swift 코드를 사용하여 대답해야합니다. –
이것은 emojis에서 작동하지 않으며 입력되는 마지막 단어 만 제공합니다. 나는 또한 그것이 커서가 현재 켜져있는 단어가되기를 원한다. 그리고 네, 신속합니다. – Tometoyou