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

后端 未结 8 1838
逝去的感伤
逝去的感伤 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:30

    Set your controller as the delegate for the text field and check if the proposed string satisfy your requirements:

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        textField.keyboardType = .decimalPad
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard 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 numberOfDots = newText.components(separatedBy: ".").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
    }
    

提交回复
热议问题