-2

How can I change a UITextField, that the User can just add one . and only two digits after the . -> Decimal Number with two digits after the poi^nt.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
Just4School
  • 117
  • 1
  • 1
  • 9

1 Answers1

1

Use 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

}
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25