限制插入 UITextField 的字符数量

Limit the amount of characters inserted into a UITextField

如何更改 UITextField,用户只需添加一个 .在 . 之后只有两位数字。 -> 小数点后有两位数的十进制数。

使用 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

}