设置UITextFieldDelegate
keyboardType = .decimalPad
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = textField.text ?? ""
if text == "0." && string.count == 0 {
textField.text = ""
return false
}
let toBeString = (text as NSString).replacingCharacters(in: range, with: string)
if string == "." && text.count == 0 {
textField.text = "0."
return false
}
if string == "." && text.contains(".") {
return false
}
if text.contains(".") && toBeString.components(separatedBy: ".").count > 1 && toBeString.components(separatedBy: ".").last?.count ?? 0 > 2 {
return false
}
return true
}
网友评论