swiftuitextfielduitextfielddelegate

custom percentage field UiTextField


i have a text field delegate method my use cases are :-

  1. if (.) dot is not there limit input to two characters because 100% should not be discount.

  2. if user input is 1.99 how can update the delegate method that it should take two numbers after (.)

  3. same if input is 12.99 how can update the delegate method that it should take two numbers after (.)

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            guard !string.isEmpty else {
                return true
            }
            
            // maximum limit of input 2 as 100% should not be discount.
            if !textField.text!.contains(".") {
                let maxLength = 2
                let currentString: NSString = (textField.text ?? "") as NSString
                let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
                return newString.length <= maxLength

            } else {
                 // if there is (.)
                 let maxLength = 3
                let currentString: NSString = (textField.text ?? "") as NSString
                let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
                return newString.length <= maxLength
            }
            
        }

Solution

  • this is the answer

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                guard !string.isEmpty else {
                    return true
                }
                let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string) as String
                if let num = Double(newText), num >= -1 && num <= 100 {
                    return true
                } else {
                    return false
                }
        
            }