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

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

    Only Two decimal point allow and only one "." allow

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
                        let text: NSString = textField.text! as NSString
                        let resultString = text.replacingCharacters(in: range, with: string)
    
    
            //Check the specific textField 
             if textField == costTextField {
                 let textArray = resultString.components(separatedBy: ".")
                 if textArray.count > 2 { //Allow only one "."
                    return false
                 }
               if textArray.count == 2 {
                  let lastString = textArray.last
                 if lastString!.count > 2 { //Check number of decimal places 
                       return false
                   }
                }
              }
               return true
           }
    

提交回复
热议问题