判断textfeild输入纯数字,长度为11
2020-06-23 本文已影响0人
存在即是美
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//设置该处 , 输入只能是数字和小数点
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let expression = "^[0-9]*([0-9])?$"
let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
if textField.text!.count == 11 {
if string.isEmpty {
return true
}else {
return false
}
}else {
return numberOfMatches != 0
}
}