How to limit the textfield entry to 2 decimal places in swift 4?

后端 未结 8 1825
逝去的感伤
逝去的感伤 2021-01-02 00:12

I have a textfield and I want to limit the entry to max 2 decimal places.

number like 12.34 is allowed but not 12.345

How do I do it?

8条回答
  •  半阙折子戏
    2021-01-02 00:35

    Following the Code Different's answer, I've improved the code to support a different Locale and different UITextFields in the same class.

      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard textField.keyboardType == .decimalPad, let oldText = textField.text, let r = Range(range, in: oldText) else {
            return true
        }
    
        let newText = oldText.replacingCharacters(in: r, with: string)
        let isNumeric = newText.isEmpty || (Double(newText) != nil)
    
        let formatter = NumberFormatter()
        formatter.locale = Locale.current
        let decimalPoint = formatter.decimalSeparator ?? "."
        let numberOfDots = newText.components(separatedBy: decimalPoint).count - 1
    
        let numberOfDecimalDigits: Int
        if let dotIndex = newText.index(of: ".") {
            numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
        } else {
            numberOfDecimalDigits = 0
        }
        return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
      }
    

提交回复
热议问题