Ashwani Kumar
Ashwani Kumar

Reputation: 555

Set the maximum amount limit on a UITextField in Swift

I know how to put character length limit on UITextField. But I am looking for an idea how to put amount limit on UITextField so that it can not take more than that limited amount.

I want to put limit on TextField that can accept value in between 0 to 1000000

I tried to get it using UITextFieldDelegate's method

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if let amount = Int(textField.text!) ,amount>1000000{
            return false
        }else{
            return true
        }
    }

but I am not able to achieve the result.

Upvotes: 2

Views: 772

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18924

You need to add the current string too with text field value.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if let text = textField.text,
           let amount = Int((text + string).trimmingCharacters(in: .whitespaces)),
           (0 < amount), (amount < 1000000) {
            return true
        }
        return false
    }

Upvotes: 4

Related Questions