iOS UITextField、UITextView处理emoji表情

在项目里可能都会用到UITextField和UITextView,用的时候键盘都可以输入emoji表情的,但有的时候后台不支持上传emoji表情,如果我们传了emoji表情会报错,由于不知道怎么禁用键盘不让输入emoji表情,所以只能在输入的时候把emoji移除,上代码:

创建 UITextField:
private lazy var searchTextField: UITextField = {
        let placeholder = NSAttributedString(string: "搜索",
                                             attributes: [.foregroundColor: UIColor.placeholder,
                                                          .font: UIFont.systemFont(ofSize: 14)])
        
        let searchTextField = UITextField().chain
            .backgroundColor(UIColor(hex: "#1D1D1D"))
            .attributedPlaceholder(placeholder)
            .tintColor(UIColor.global)
            .textColor(UIColor.white)
            .clearButtonMode(.whileEditing)
            .systemFont(ofSize: 14)
            .leftViewMode(.always)
            .masksToBounds(true)
            .build
        if let clearButton = searchTextField.value(forKey: "_clearButton") as? UIButton {
            clearButton.setImage(#imageLiteral(resourceName: "login_text_field_clear"), for: .normal)
        }
        
        return searchTextField
}()
添加到View上:
view.addSubview(searchTextField)
searchTextField.snp.makeConstraints { (make) in
    make.left.equalTo(view.snp.left).offset(20)
    make.top.equalTo(view.snp.top).offset(100)
    make.right.equalTo(view.snp.right).offset(-20)
    make.height.equalTo(50)
}
添加通知监听UITextField输入:
private func addNSNotificationCenter() {
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextChange(noti:)), name: NSNotification.Name.UITextFieldTextDidChange, object: searchTextField)
}

@objc private func textFieldTextChange(noti: Notification) {
        if let textField = noti.object as? UITextField {
            if textField.markedTextRange == nil {
                if var text = textField.text {
                    textField.text = text
                } else {
                    textField.text = ""
                }
            }
        }
}

这样是可以输入emoji表情的,所以还得在输入的时候把emoji移除掉,写一个extension:

extension String {
    // 移除emoji
    func removeEmoji() -> String {
        let pattern = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"
        return self.pregReplace(pattern: pattern, with: "")
    }

    //返回字数
    var count: Int {
        let string_NS = self as NSString
        return string_NS.length
    }
    
    //使用正则表达式替换
    func pregReplace(pattern: String, with: String,
                     options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
}

在监听里面(textFieldTextChange)调用一下 removeEmoji() 就可以了:

@objc private func textFieldTextChange(noti: Notification) {
        if let textField = noti.object as? UITextField {
            if textField.markedTextRange == nil {
                if var text = textField.text {
                    text = text.removeEmoji()
                    textField.text = text
                } else {
                    textField.text = ""
                }
            }
        }
}

好了,到这就结束了,最后再附上一个判断是否包含emoji表情的方法:

extension String {
   // 判断是否包含emoji
   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
   }
}

你可能感兴趣的:(iOS UITextField、UITextView处理emoji表情)