ios – “无法递增endIndex” – 由于UITextView中的表情符号字符而出错

我有UITextView的扩展:

extension UITextView {

    func separatedWordsInFrontCursor(infront: Bool = true) -> [String] {

        let cursorPosition = selectedRange.location
        let separationCharacters = NSCharacterSet(charactersInString: " ")

        let beginRange = Range(start: text.startIndex.advancedBy(0), end: text.startIndex.advancedBy(cursorPosition))
        //fatal error: can not increment endIndex

        let endRange = Range(start: text.startIndex.advancedBy(cursorPosition), end: text.startIndex.advancedBy(text.characters.count))

        let beginPhrase = text.substringWithRange(beginRange)
        let endPhrase = text.substringWithRange(endRange)

        return infront ? beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters) : endPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
    }
}

错误如下:

fatal error: can not increment endIndex

这是我尝试输入UITextView:《ios – “无法递增endIndex” – 由于UITextView中的表情符号字符而出错》

UITextView的键盘类型设置为“默认”.

出现错误时:

cursorPosition is 3
text.characters.count is 2
text.startIndex is 0
text.startIndex.advancedBy(2) is 3
text.startIndex.advancedBy(cursorPosition) is "fatal error: can not increment endIndex"

我该如何解决这个问题?

最佳答案 正如@Martin R所说,我们需要对NSRange和NSString进行操作,因此解决方案如下:

private func separatedWordsInFrontCursor(infront: Bool = true) -> [String] {

    let cursorPosition = selectedRange.location
    let separationCharacters = NSCharacterSet(charactersInString: " ")

    let nstext = NSString(string: text)

    let beginRange = NSRange(location: 0, length: cursorPosition)
    let endRange = NSRange(location: cursorPosition, length: nstext.length - cursorPosition)

    let beginPhrase = nstext.substringWithRange(beginRange)
    let endPhrase = nstext.substringWithRange(endRange)

    return infront ? beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters) : endPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
}
点赞