Set maximum length of textfield for multiple text fields

I am making an app where I have multiple text fields and I need to set a maximum character length for each. Note: Each textfield will have a different maximum length.


So far I have tried:


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let maxLength = 30
        let currentString: NSString = brandTextField.text! as NSString
        
        let newString: NSString =
            currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }

But this only works for one text field and I can't specify different lengths for different text fields.


Thanks for any help with this matter!

Accepted Reply

You need a property for each one of your textFields:


let textFieldOne: UITextField
let textFieldTwo: UITextField
let textFieldThree: UITextField


Then in the function you check wich textfield is:


    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let maxLength : Int
        
        if textField == textFieldOne{
            maxLength = 30
        } else if textField == textFieldTwo{
            maxLength = 20
        } else if textField == textFieldThree{
            maxLength = 40
        }
        
        let currentString: NSString = textField.text! as NSString
        
        let newString: NSString =  currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }

Replies

You need a property for each one of your textFields:


let textFieldOne: UITextField
let textFieldTwo: UITextField
let textFieldThree: UITextField


Then in the function you check wich textfield is:


    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let maxLength : Int
        
        if textField == textFieldOne{
            maxLength = 30
        } else if textField == textFieldTwo{
            maxLength = 20
        } else if textField == textFieldThree{
            maxLength = 40
        }
        
        let currentString: NSString = textField.text! as NSString
        
        let newString: NSString =  currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }

Set Maximum length for multiple Textfields works lkie charm for me. I was Making UI like entering PIN code for 4 digits. So worked nicely.