Home > Software design >  How to compare textfield entered amount with total amount in textfield delegate method in swift
How to compare textfield entered amount with total amount in textfield delegate method in swift

Time:08-24

I need to compare entered textfield value with totalValue then need to show one error message in red colour

for that i have tried below code: here my total amount is 180... i need to show the red coloured text if i enter 181 in textfield but its showing only if i enter 4 characters for eg.. 1811 then its showing but i need immediately after i enter 181 in textfield... where am i wrong? please guide me.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(string)
if textField == self.amountTextField {
    if let char = string.cString(using: String.Encoding.utf8) {
        let isBackSpace = strcmp(char, "\\b")
        let enteredAmount = textField.text
        let totalAmnt = 180

        if enteredAmount?.toInteger() ?? 0 >= totalAmnt.toInteger(){
            amntErrorLbl.text = "Payment being made is more than quote"
        }
    }
}
return true
} 

o/p screenshots:

if i enter 181 in textfield then o/p

if i add 4 numbers then o/p

CodePudding user response:

var totalAmount = 180

func textFieldDidChangeSelection(_ textField: UITextField) {
    guard let text = textField.text,text.isNumbers else {
        return
    }
    guard let enteredAmount = Int(text) else {
        return
    }
    if enteredAmount > totalAmount {
        amntErrorLbl.text = "Entered more than total amount"
    }
    if enteredAmount < totalAmount {
        amntErrorLbl.text = "Entered less than total amount"
    }
    if enteredAmount == totalAmount {
        amntErrorLbl.text = "Entered equal amount"
    }
    
}


extension String {
    var isNumbers:Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}
  • Related