Search code examples
swiftuitextfieldcharacteruitextfielddelegate

Swift: Limit Characters # in textField without disabling/interfering with other functions


I want to limit the number of characters a user can use in a textField. I took a function from this link: Max length UITextField (Imanou Petit)

However, in my viewDidLoad() I have several textFields that I'm already referencing the delegate because I want the keyboard to "Return" when the user presses the Return key on the keyboard. This I'm doing through the textFieldShouldReturn like this (I also have a touchesBegan method but I want the user to also have the option of the Return key):

 func textFieldShouldReturn(textField: UITextField!) -> Bool {


 self.stuffOneTextField.resignFirstResponder()
    self.linkTextField.resignFirstResponder()
    self.descriptionTextField.resignFirstResponder()
    self.ogTextField.resignFirstResponder()
    self.priceTextField.resignFirstResponder()

    return true

}

If I add in this function below to the viewDidLoad, then the 'Return' key on the keyboard doesn't work and it limits ALL of the textFields (I have 5).

 override func viewDidLoad() {
    super.viewDidLoad()


    self.stuffOneTextField.delegate = self
    self.linkTextField.delegate = self
    self.descriptionTextField.delegate = self
    self.ogTextField.delegate = self
    self.priceTextField.delegate = self
}

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= limitLength
   }

I only need to limit 2 textFields. I've tried just putting in the specific textField name instead of all the textFields as textFields and then it limits 1 textField and doesn't let me type in the others... Very strange...

How do I go around this?

Any help means a lot.


Solution

  • You're being given the textField that is changing characters in the delegate function. Here, you can compare it to the specific fields that you want to limit:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return true }
        if !(textField == stuffOneTextField || textField == descriptionTextField) {
            return true
        }
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= limitLength
    }
    

    Also, func textFieldShouldReturn(textField: UITextField!) -> Bool is giving you a text field, and you can call resignFirstResponder() on that, if that is what you want to do there.