Swift输入框过滤表情

Swift输入框过滤表情

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        var isText = true
        if text.containsEmoji {
            if String.isInputRuleNotBlank(str: text) {
                isText = true
            } else {
                isText = false
            }
        }
        
        return isText
        
    }







extension String {

    // 是否包含表情
    var containsEmoji: Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case
            0x00A0...0x00AF,
            0x2030...0x204F,
            0x2120...0x213F,
            0x2190...0x21AF,
            0x2310...0x329F,
            0x1F000...0x1F9CF:
                return true
            default:
                continue
            }
        }
        return false
    }

    /**
     * 字母、数字、中文正则判断(不包括空格)
     *注意: 因为考虑到输入习惯,许多人习惯使用九宫格,这里在正常选择全键盘输入错误的时候,进行九宫格判断,九宫格对应的是下面➋➌➍➎➏➐➑➒的字符
     */
    static func isInputRuleNotBlank(str:String) -> Bool {
        let pattern = "^[a-zA-Z\\u4E00-\\u9FA5\\d]*$"
        let pred = NSPredicate(format: "SELF MATCHES %@", pattern)
        let isMatch = pred.evaluate(with: str)
        if !isMatch {
            let other = "➋➌➍➎➏➐➑➒"
            let len = str.characters.count
            for i in 0.. 0 || (isalnum(Int32(c))) > 0 || ((Int(c) == "_".hashValue)) || (Int(c) == "-".hashValue) || ((c >= 0x4e00 && c <= 0x9fa6)) || (tmpOther.range(of: str).location != NSNotFound)) {
                    return false
                }
                return true
            }
        }
        return isMatch
    }


    // MARK: 过滤字符串中的特殊字符
    public func stringReplacingOccurrencesOfString() {
        
        let str: NSString = self as NSString
        
        let charactersInString = "[]{}(#%-*+=_)\\|~(<>$%^&*)_+ "
        let doNotWant = CharacterSet.init(charactersIn: charactersInString)
        
        let componentsArrays = str.components(separatedBy: doNotWant)
        let hmutStr = componentsArrays.joined(separator: "")
        print("humStr is:\(hmutStr)")
    }



}


 

你可能感兴趣的:(《iOS开发之路》,《Swift开发之路》)