How to set maximum size of 2 textfields separately (Swift)

Asked

Viewed 127 times

0

Next, I’m starting now with Swift and iOS programming. I have a question: how to validate 2 different textFields? For example, I managed with the code below to validate 1 single field, but the problem that my application has 4 fields and this validation is counting the characters of all fields. Like, if the textField that I put there on the "Return" hits the maxCharCount, besides locking this textField, it hangs all the next ones as well. How to make it validate each field separately?

func textField(_ shouldChangeCharactersIntextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    return textField.text!.characters.count + string.characters.count <= self.maxCharCount

}

I have tried several ways: create a function for each textField, join the 4 textfields inside the Return, chained if, everything the Xcode complains or does not work the right way. Someone’s been there and they’d know to help me?

1 answer

1

Hello,

You can differentiate each UITextField:

@IBOutlet weak var meuTextField1: UITextField!
@IBOutlet weak var meuTextField2: UITextField!    

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if  textField == meuTextField1 {
        // algoritmo aqui
        // return true|false
    }
    if  textField == meuTextField2 {
        // algoritmo aqui
        // return true|false
    }
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.