///限制小数点后两位
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string == "." || string == "0" else {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if newString.range(of: ".") == nil {
if (newString as NSString).length > 1 && newString.hasPrefix("0") {
return false
}
}
return newString.isValidAmount()
}
guard let text = textField.text else { return true }
if text.count == 0 {
textField.text = "0."
return false
}
if text.range(of: ".") == nil && string == "0" {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if !text.hasPrefix("0") && newString.isValidAmount() {
return true
}
return false
}
if text.range(of: ".") != nil && string == "." {
return false
}
if text.range(of: ".") != nil {
let list = textField.text!.components(separatedBy: ".")
let last = list.last!
return (last as NSString).length < 2
}
return true
}
extension String {
public func isValidAmount() -> Bool {
let expression = "^[0-9]{0,9}?$*((\\.|,)[0-9]{0,2})?$"
let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex.numberOfMatches(in: self, options:.reportProgress, range: NSMakeRange(0, (self as NSString).length))
return numberOfMatches != 0
}
}
网友评论