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

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

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                let dotString = "."
    
                if let text = textField.text {
                    let isDeleteKey = string.isEmpty
    
                    if !isDeleteKey {
                        if text.contains(dotString) {
                            if text.components(separatedBy: dotString)[1].count == 2 {
    
                                        return false
    
                            }
    
                        }
    
                    }
                }
                return true
             }
    

提交回复
热议问题