如何在UITextView中检测@符号输入后的字符串?遇返回异常问题
解决UITextView中@符号后无法获取后续字符串的问题
Hey Chris, let's tackle this @mention detection issue you're stuck on! You mentioned you've got the @ symbol detected, but can't pull the subsequent string properly—let's work through this step by step.
常见问题原因
- 光标位置与字符串索引的转换逻辑出错,导致截取范围无效
- 没有处理多个@符号的场景,误取了较早的@后面的内容
setTextTyping方法的参数传递或内部处理存在问题
修正后的实现示例
这里是调整后的textViewDidChange方法,重点优化了@后字符串的截取逻辑:
func textViewDidChange(_ textView: UITextView) { guard let commentText = commentTextView.text else { return } commentString = commentText // 定位到文本中最后一个@符号(处理多@场景) guard let atRange = commentText.range(of: "@", options: .backwards) else { // 没有@符号时的处理逻辑 commentTextView.setTextTyping(text: commentText, withHashtagOrMention: "") return } // 计算@符号后的起始索引 let mentionStartIndex = commentText.index(after: atRange.lowerBound) // 获取当前光标位置对应的字符串索引 let cursorPosition = commentText.index(commentText.startIndex, offsetBy: textView.selectedRange.location) // 确保截取范围合法,避免索引越界崩溃 guard mentionStartIndex < cursorPosition else { commentTextView.setTextTyping(text: commentText, withHashtagOrMention: "") return } // 截取@符号到光标之间的字符串 let currentMentionText = String(commentText[mentionStartIndex..<cursorPosition]) // 传入你的setTextTyping方法进行后续处理 commentTextView.setTextTyping(text: commentText, withHashtagOrMention: currentMentionText) }
关键逻辑说明
- 使用
.backwards选项查找最后一个@符号,确保获取的是用户当前正在输入的@提及内容 - 严格处理光标位置与字符串索引的转换,避免因索引越界导致的崩溃或空值
- 增加了边界判断,在没有@符号或光标位于@之前时,传入空字符串做兼容处理
如果你的setTextTyping方法还有内部逻辑问题,可以把它的代码贴出来,我们再进一步排查!
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

