Home > Software engineering >  How to set up UITextFieldDelegate for multiple text fields?
How to set up UITextFieldDelegate for multiple text fields?

Time:03-01

I can't run code like this, what's wrong? It doesn’t work for all textfield, but rather only one of them.

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

    let newlenght1 = (textField1.text?.utf16.count)!   string.utf16.count - range.length // I have 3 textfield and I want for all of them same rule
    let newlenght2 = (textField2.text?.utf16.count)!   string.utf16.count - range.length // I have 3 textfield and I want for all of them same rule
    let newlenght3 = (textField3.text?.utf16.count)!   string.utf16.count - range.length // I have 3 textfield and I want for all of them same rule
    let allowedCharacters = "ABCDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ" // I only this charachters // allowed characters
    let characthers = CharacterSet(charactersIn: allowedCharacters)
    let charactersType = CharacterSet(charactersIn: string)
    let finalCharacters = characthers.isSuperset(of: charactersType)
    
    if textField == textField1 && textField == textField2 && textField == textField3 && newlenght1 <= 1 && newlenght2 <= 1 && newlenght3 <= 1 {
        return finalCharacters // but don't work for all textfield ,worked for only 1 textfield
    }else{
        return false
    }   
}

CodePudding user response:

If your goal is to have all three text fields follow the same rule, set the delegate for all three. The shouldChangeCharactersIn only needs to check the “current” text field into which the user is currently typing.

A minor observation, but I also would avoid recreating the CharacterSet of allowed characters repeatedly. You can simply make that a property.

That reduces it down to something like:

private let allowedCharacters = CharacterSet(charactersIn: "ABCDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ")

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField.text?.count ?? 0)   range.length > 1 {
        return false
    }
    
    return allowedCharacters.isSuperset(of: CharacterSet(charactersIn: string))
}
  • Related