限制输入框只能输入两位小数
限制输入框只能输入两位小数,如果一开始输入0,然后再次输入数字。默认在中间给添加上小数点。
/// 输入框限制数字
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = textField.text ?? ""
if !Tool.isNumberAndTwoDecimalContent(string: text + string) {
if text.count > 0, string == ".", !text.contains(".") {
return true
}
return false
} else {
if textField.text == "0", Tool.isNumberContent(string: string) {
textField.text = "0."
}
}
return true
}
/**
* 判断只能输入数字和小数点后两位
*/
static func isNumberAndTwoDecimalContent(string:String) -> Bool {
let regex = "^[0-9]+(\\.[0-9]{1,2})?$"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
let isValid = predicate.evaluate(with: string)
return (isValid ? true : false)
}
/**
* 判断只能输入数字
*/
static func isNumberContent(string:String) -> Bool {
let scan: Scanner = Scanner(string: string)
var val:Int = 0
return scan.scanInt(&val) && scan.isAtEnd
}
网友评论