我正在尝试在具有字符串值的textView中添加表情符号,但是当我在textView应用程序中输入文本时崩溃并给我错误:
致命错误:不能增加到endIndex以外
func currentWord (_ selectedRange: NSRange, _ text: String) -> String? {
let regex = try! NSRegularExpression(pattern: "\\S+$")
let textRange = NSRange(location: 0, length: selectedRange.location)
if let range = regex.firstMatch(in: text, range: textRange)?.range {
let start = text.index(text.startIndex, offsetBy: range.location)
// Error is on the following line
let end = text.index(start, offsetBy: range.length)
return String(text[start..<end])
}
return nil
}
答案 0 :(得分:3)
您用于计算String.Index
的代码是错误的。 text
中包含非BMP字符(例如,表情符号)时,此功能不起作用。
尝试一下:
func currentWord(_ selectedRange: NSRange, _ text: String) -> String? {
let regex = try! NSRegularExpression(pattern: "\\S+$")
let textRange = NSRange(location: 0, length: selectedRange.location)
if let range = regex.firstMatch(in: text, range: textRange)?.range {
let indexRange = Range<String.Index>(range, in: text)!
return String(text[indexRange])
}
return nil
}