TextField
1.给textField 添加监听
NotificationCenter.default.addObserver(self, selector:
#selector(textFieldChanged), name:
NSNotification.Name(rawValue:
"UITextFieldTextDidChangeNotification"),
object:self.nameTextField)
2.实现监听方法
@objc func textFieldChanged(obj:Notification) {
let limit : Int = 4
let textField : UITextField = obj.object as! UITextField
//非markedText才继续往下处理
guard let _: UITextRange = textField.markedTextRange else{
textField.text = filtercharactor(searchText: (textField.text ?? ""), regexStr: "[^\u{4e00}-\u{9fa5}]")
if(textField.text! as NSString).length > limit{
MBProgressHUD.xy_hide()
MBProgressHUD.xy_show("最多支持4个字哦")
textField.text = (textField.text! as NSString).substring(to:limit)
}
return
}
}
限制只输入汉字
func filtercharactor(searchText: String,regexStr: String) -> String? {
if let regex = try? NSRegularExpression.init(pattern: regexStr, options: .caseInsensitive) {
let resultStr = regex.stringByReplacingMatches(in: searchText, options: .reportCompletion, range: NSRange(location: 0, length: searchText.count), withTemplate: "")
return resultStr
}else{
return nil
}
}
TextView
func textViewDidChange(_ textView: UITextView) {
let limit = 100
if textView.text.count > limit {
textView.text = String(textView.text.prefix(limit))
textView.undoManager?.removeAllActions()
textView.becomeFirstResponder()
return
}
}
网友评论