Search code examples
iosios5ios4

How to limit the characters of textfield in iOS application up to 5 characters?


I would like to limit the characters in textField of IOS Application. I tried all the methods given in Stack Overflow, so I am asking this question.

Here I used one Label (secure code) and one textfield (5 characters).

I had given the below code in viewcontroller.m file, but not working.

   myTextField.delegate = self

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
   NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

   return !([newString length] > 5);
}

Solution

  • In ViewController.h, <UITextFieldDelegate> should be added.

    In your viewDidLoad, myTextField.delegate = self should be added.

    And then, to limit the number of characters:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string
    {
         if (textField.text.length >= 5 && range.length == 0)
            return NO;
         return YES;
    }
    

    Works for me. Try it.

    EDIT:

    On the other hand, your code should work perfectly fine as well. Check your code again.