iOS:TextView删除@内容

2021-08-26  本文已影响0人  _GXT
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
    }
上一篇下一篇

猜你喜欢

热点阅读