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

0

Next, I'm now starting with Swift and iOS programming. I have a question: how to validate 2 different textFields? For example, I managed with the code below to do the validation of 1 single field, but the problem that my application has 4 fields and this validation is counting the characters of all fields. Type, if the textField that I put there in the "return" reaches the maxCharCount, in addition to locking this textField, it locks all the next ones as well. How do I 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 in several ways: create a function for each textField, join the 4 textfields inside the return, if chained, all xcode complains or does not work the right way. Has anyone been through this and would you be able to help me?

    
asked by anonymous 27.03.2017 / 01:30

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
    }
    ...
}
    
28.03.2017 / 20:23