swift3.0版UITextField文字输入限制加emoj表情过滤

懒加载控件

 //昵称
    fileprivate lazy var  nameTextfield:UITextField = {
        let nameTextfield = UITextField()
        nameTextfield.textColor = cmColorWithString(colorName: "666666")
        nameTextfield.font = UIFont.systemFont(ofSize: 13)
        nameTextfield.textAlignment = .right
        nameTextfield.delegate = self
        return nameTextfield
    }()

添加通知

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        NotificationCenter.default.addObserver(self, selector: #selector(TextDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }

TextDidChange方法

func TextDidChange(){
        
        let str = nameTextfield.text
        if !self.isInputRuleAndBlank(str: str!){
            nameTextfield.text = self.disable_emoji(str: str!)
        }
        let lang = nameTextfield.textInputMode?.primaryLanguage
        if lang == "zh-Hans"{
            let selectedRange = nameTextfield.markedTextRange
            
            if let _ = selectedRange{
                
            }else{
                let getStr = self.getSubString(str: str!)
                if getStr != ""  && getStr.characters.count>0{
                    nameTextfield.text = getStr
                }
            }
            
        }else{
            let getStr = self.getSubString(str: str!)
            if getStr != ""  && getStr.characters.count>0{
                nameTextfield.text = getStr
            }
        }
    }

TextField代理方法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if self.isInputRuleNotBlank(str: string) || string == ""{
            return true
        }else{
            return false
        }
    }
 * 字母、数字、中文正则判断(包括空格)(在系统输入法中文输入时会出现拼音之间有空格,需要忽略,当按return键时会自动用字母替换,按空格输入响应汉字)
 */
    func isInputRuleAndBlank(str:String)->Bool{
        let pattern = "^[a-zA-Z\\u4E00-\\u9FA5\\d\\s]*$"
        let pred = NSPredicate(format: "SELF MATCHES %@", pattern)
        let isMatch = pred.evaluate(with: str)
        return isMatch
    }
    ```

    /**
     *  过滤字符串中的emoji
     */
func disable_emoji(str:String)->String{
    let regex = try!NSRegularExpression.init(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: .caseInsensitive)
    
    let modifiedString = regex.stringByReplacingMatches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: str.characters.count), withTemplate: "")
    return modifiedString
}
    /**
     * 字母、数字、中文正则判断(不包括空格)
     *注意: 因为考虑到输入习惯,许多人习惯使用九宫格,这里在正常选择全键盘输入错误的时候,进行九宫格判断,九宫格对应的是下面➋➌➍➎➏➐➑➒的字符
     */

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
}

    /**
     *  获得 CharacterCount长度的字符
     */
func getSubString(str:String) -> String{
    if str.characters.count>15{
        self.view.ShowMbProgressHUD(message: "最多输入15个字")
        return str[0..<(15)]
    }
    return str
}
截取字符串扩展

extension String {
subscript (r: Range) -> String {
get {

        let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let endIndex =   self.index(self.startIndex, offsetBy: r.upperBound)
        return self[Range(startIndex..

}

你可能感兴趣的:(swift3.0版UITextField文字输入限制加emoj表情过滤)