3

I have the app for Celectial navigation calculations, I have converted in code textField.text to Double, but some times app crashing if user input some fields like "1.0" and some like "1", in result app crashing because can't deduct Int and Double, to be sure I want to restrict user to input only decimal digits "1.0". The best way for me is to code something like if the user enters for example "1" automatically after pressing the done button, add ".0" to get 1.0?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "-1234567890."
        let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
        let typedCharactersSet = CharacterSet(charactersIn: string)
        return allowedCharacterSet.isSuperset(of: typedCharactersSet)

    }




     func TextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = latDegTextField.text else { return true }
        let count = text.count + string.count - range.length
        return count == 2
    }

2 Answers2

2

First of all use this method from HERE which is

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text != "" || string != "" {
        let res = (textField.text ?? "") + string
        return Double(res) != nil
    }
    return true
}

And in your done button action add this:

@IBAction func btnDoneTapped(_ sender: Any) {

    print(tf.text)
    guard let obj = Double(tf.text!) else { return }
    print(obj)
}

And when you enter 1 and press done button print(tf.text) will print Optional("1") and print(obj) will print 1.0

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
1

Use this code :-

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //Will prevent user from entering space as first character
        let enteredCharString = "\(textField.text ?? "")\(string )"
        if enteredCharString.trimmingCharacters(in: .whitespaces).count == 0 {
            return false
        }
        switch textField {
        case txt_Ammount:
            if txt_Ammount.text != "" || string != "" {
                let res = (txt_Ammount.text ?? "") + string
                return Double(res) != nil
            }
        default:
            true
        }



        return true

    }
NavinBagul
  • 741
  • 7
  • 24