gpt4 book ai didi

ios - "cannot increment endIndex"- 由于 UITextView 中的表情符号字符而出错

转载 作者:搜寻专家 更新时间:2023-10-31 19:38:26 26 4
gpt4 key购买 nike

我有 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 中输入的内容:enter image description here

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 所说,我们需要对 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)
}

关于ios - "cannot increment endIndex"- 由于 UITextView 中的表情符号字符而出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34611470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com