我正在尝试在textField中为数量添加一些验证。我正在尝试允许用户使用十进制键盘添加有效数字。 用户可以添加小于100000的数字(99999.99,9999,9,1) 用户无法添加[12 ..,12.0.2,12.345,100.23456
等数字这是我尝试过的。 如果我尝试将最大长度添加到5.i无法添加99999.99。 如果我将最大长度添加到8.我可以添加超过99999的数字。 希望你明白我的问题。谢谢你提前
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 5
var newString : NSString = ""
if(textField.tag == 3){
let currentString: NSString = tvAmount.text! as NSString
newString =
currentString.replacingCharacters(in: range, with: string) as NSString
// max 2 fractional digits allowed
let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let regex = try! NSRegularExpression(pattern: "\\..{3,}", options: [])
let matches = regex.matches(in: newText, options:[], range:NSMakeRange(0, newText.characters.count))
guard matches.count == 0 else { return false }
if(newString.length < 5){
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = textField.text?.characters.map { String($0) }
var decimalCount = 0
for character in array! {
if character == "." {
decimalCount = decimalCount + 1
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = string.characters.map { String($0) }
if array.count == 0 {
return true
}
return false
}
}
else{
}
}
return newString.length <= maxLength
}