func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// //第一个参数,被替换字符串的range,第二个参数,即将键入或者粘贴的string,返回的是改变过后的新str,即textfield的新的文本内容
let oldText: NSString = textField.text! as NSString
let checkStr = oldText.replacingCharacters(in: range, with: string)
if checkStr.count == 0 {
return true
}
if textField == self.tf_money{
let regex = "^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$"
let predicte = NSPredicate(format: "SELF MATCHES %@", regex)
let isValid = predicte.evaluate(with: checkStr)
return isValid
}
if textField == self.tf_num{
let regex = "^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$"
let predicte = NSPredicate(format: "SELF MATCHES %@", regex)
let isValid = predicte.evaluate(with: checkStr)
return isValid
}
return true
}
网友评论