1

swift - limit text characters on two different textfields in the same VC

I want to make one text field only allow someone to type in 10 characters and in the second text field they can type in 20 characters and just not sure how to put this into the one shouldchangecharacter func as im guessing you dont do two seperate functions because that isn't working for me?

// text field 1

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

    let currentCharacterCount = textfield1.text?.characters.count ?? 0

if (range.length + range.location > currentCharacterCount){
    return false

}
let newLength = currentCharacterCount + string.characters.count - range.length


return newLength <= 10

}

// text field 2

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

    let currentCharacterCount2 = TextField2.text?.characters.count ?? 0

    if (range.length + range.location > currentCharacterCount2){
        return false

    }
    let newLength = currentCharacterCount2 + string.characters.count - range.length


    return newLength <= 20

}
benpalmer661
  • 49
  • 10

1 Answers1

2

If you have outlets to both text fields in your view, then you can do something like this:

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

    let currentCharacterCount = textField.text?.characters.count ?? 0

    if (range.length + range.location > currentCharacterCount){
        return false

    }
    let newLength = currentCharacterCount + string.characters.count - range.length

    var maxLength = 0
    if textField.isEqual(textField1) {
        maxLength = 10
    } else if textField.isEqual(textField2) {
        maxLength = 20
    }

    return newLength <= maxLength

}

Just replace the two text field names with whatever your outlets are named :)

Nick
  • 158
  • 1
  • 5