本片分两部分
1、使用正则表达式过滤表情
2、处理苹果自带键盘无法输入汉字问题
先记录下,后面完善:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldEditChanged(noti:)), name: Notification.Name.UITextFieldTextDidChange, object: self.inputTextField)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UITextFieldTextDidChange, object: self.inputTextField)
}
@objc fileprivate func textFieldEditChanged(noti: Notification) {
guard let textField = noti.object as? UITextField else {
return
}
// 有高亮的正在输入的字符,不做任何处理
if let _ = textField.markedTextRange {
return
}
guard let endRange = textField.selectedTextRange?.end else {
return
}
guard let regexStr = self.stepType.inputRegex else {
return
}
let cursorPositon = textField.offset(from: textField.endOfDocument, to: endRange)
// 使用正则过滤字符串
let resultStr = Utils.regularRepalce(regexStr, origin: textField.text ?? "")
textField.text = resultStr
if let targetPosition = textField.position(from: textField.endOfDocument, offset: cursorPositon) {
textField.selectedTextRange = textField.textRange(from: targetPosition, to: targetPosition)
}
}
使用给定的正则匹配,不匹配的字符使用空串过滤
/// 对给入的字符串进行正则,未匹配的使用相应的字符替换
///
/// - Parameters:
/// - regexStr: 正则
/// - origin: 原始字符串
/// - template: 喜欢的字符串
/// - Returns: 返回正则处理之后的字符串
public static func regularRepalce(_ regexStr: String, origin: String, template: String = "") -> String {
guard let regex = try? NSRegularExpression(pattern: regexStr, options: []) else {
return origin
}
return regex.stringByReplacingMatches(in: origin, options: [], range: NSRange(location: 0, length: origin.count), withTemplate: template)
}
我使用的正则
1、匹配所有非 空格大小写字母数字中文和下划线 -
"[^ A-Za-z0-9\\u4E00-\\u9FA5_-]" // 中英文空格_-,其他过滤
"[^A-Za-z0-9]" // 非英文数字