1 // MARK: - UITextFieldDelegate 2 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) - Bool { 3 guard string == " . " || string == " 0 " else { 4 //限制输入个数{0,2},0-
1 // MARK: - UITextFieldDelegate 2 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 3 guard string == "." || string == "0" else { 4 //限制输入个数{0,2},0-2 5 /* 6 let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) 7 8 //纯整数,限制只有6位{0,6}。如果是小数,就小数点前6后8位{0,8} 9 //let expression = "^[0-9]{0,6}?$*((\\.|,)[0-9]{0,8})?$" 10 let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$" 11 let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace) 12 let numberOfMatches = regex.numberOfMatches(in: newString, options:.reportProgress, range: NSMakeRange(0, (newString as NSString).length)) 13 return numberOfMatches != 0 14 */ 15 16 //无限制 17 return true 18 } 19 20 guard let text = textField.text else { return true } 21 if text.count == 0 { 22 textField.text = "0." 23 return false 24 } 25 26 if text.range(of: ".") != nil && string == "." { 27 return false 28 } 29 30 return true 31 }