如何更改UITextField,使用户可以仅添加一个。并且在。之后仅两位数字。 ->小数点后加两位数。
答案 0 :(得分:0)
使用UITextFieldDelegate
// MARK:- TEXTFIELD DELEGATE
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
let countdots = (txf_Amount.text?.components(separatedBy: ".").count)! - 1
if countdots > 0 && string == "."
{
return false
}
let MAX_BEFORE_DECIMAL_DIGITS = 7
let MAX_AFTER_DECIMAL_DIGITS = 3
let computationString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
// Take number of digits present after the decimal point.
let arrayOfSubStrings = computationString.components(separatedBy: ".")
if arrayOfSubStrings.count == 1 && computationString.characters.count > MAX_BEFORE_DECIMAL_DIGITS {
return false
} else if arrayOfSubStrings.count == 2 {
let stringPostDecimal = arrayOfSubStrings[1]
return stringPostDecimal.characters.count <= MAX_AFTER_DECIMAL_DIGITS
}
return true
}