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

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

    Guys, here's the solution:

     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
    
                        }
    
                    }
    
                }
            }
      }
    

提交回复
热议问题