美文网首页
iOS:TextView删除@内容

iOS:TextView删除@内容

作者: _GXT | 来源:发表于2021-08-26 17:22 被阅读0次
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            
            // 固定格式 必须为 "@xxx "  @开头,空格结尾
            // 一次性删除 @xxx 这种 @ 消息
            
            if text != "" {
                return true
            }
            
            // 转为OC字符串,因为swift对字符串操作比较麻烦
            let ocString = textView.text as NSString?
            
            guard let ocResultString = ocString else { return true }
            
            if ocResultString.length == 0 {
                return true
            }
            
            // 32是空格的ascii码
            let blank = 32
            // '@' 对应的ascii码
            let at = 64;
            
            // 判断是否是空格
            let blankChar = ocResultString.character(at: range.location)
            if blankChar != blank {
                return true
            }
            
            // 如果是空格回溯找到@
            var location = range.location
            var length = range.length
            
            
            while location != 0 {
                location = location - 1
                length = length + 1
                
                // 获取字符
                let subChar = ocResultString.character(at: location)
                
                // 如果发现了其他空格,说明是"@xxx xxx"
                if subChar == blank {
                    return true
                }
                
                if subChar != at {
                    continue
                }
                
                // 找到了@
                let atText = ocResultString.substring(with: NSMakeRange(location, length))
                print("@的内容是:\(atText)")
                let afterText = ocResultString.replacingCharacters(in: NSMakeRange(location, length), with: "")
                
                textView.text = afterText
                
                return false
                
            }
            
            return true
        }
    

    相关文章

      网友评论

          本文标题:iOS:TextView删除@内容

          本文链接:https://www.haomeiwen.com/subject/yuuuiltx.html