Mohith P Mohith P - 5 months ago 18
iOS Question

Set limit to UITextField in ObjectiveC

I am creating login screen using Objective C in which i want to implement validation for User name(E-Mail) and password.How to implement this in very simple way.

Answer

You can always make use textField shouldChangeCharactersInRange delegate to handle the number of characters allowed in textField. Have look at the solution provided below :) Hope it helps

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        if(textField == self.emailTextField){
            if (textField.text.length < 30 || string.length == 0){ 
                return YES;
            }
            else{
                return NO;
            }
        }
    }

EDIT

As per your comments you are not recieveing the textField delegates, so here is what you can do :)

In your ViewController, confirm the UITextFieldDelegate using,

YourViewController : UIViewController <UITextFieldDelegate>

In your viewDidLoad or ViewWillAppear set the textField delegate as self.

self.emailTextField.delegate = self;
Comments