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

时间:2016-01-05 12:14:57

标签: ios swift uitextview emoji

我有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)
    }
}

错误如下:

  

致命错误:无法递增endIndex

这是我尝试输入UITextViewenter image description here

的内容

UITextView的键盘类型设置为Default

出现错误时:

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"

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

正如@Martin R所说,我们需要对NSRangeNSString进行操作,因此解决方案如下:

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)
}