1

can any body tell me how to set the limit for words to enter in a text field in objective-c? In my case i have a registration form and in registration form every user have to enter username, password, email and phone no. and now i have to restrict the user to enter a name of maximum 15 characters.

can any one tell me how i can do this?

Mashhadi
  • 3,004
  • 3
  • 46
  • 80
  • 2
    possible duplicate of [iPhone SDK: Set Max Character length TextField](http://stackoverflow.com/questions/433337/iphone-sdk-set-max-character-length-textfield) – George Johnston Jul 27 '11 at 16:34
  • This post likely has what you are looking for: http://stackoverflow.com/questions/433337/iphone-sdk-set-max-character-length-textfield – AlexFZ Jul 27 '11 at 16:35

2 Answers2

2

You are able to restrict number of inputs in UITextField both following ways.

First of all, set relevant UIViewController as a delegate object to UITextField

yourTextField.delegate = self;

Then add the following code snippet to your UIViewController.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length]<15) {
           return YES;
    }

    return NO;
}

Or you can define UITextFieldDelegate protocol in your UIViewController interface

@interface YourViewController()<UITextFieldDelegate>
  // YourViewController.m
@end

and then implement the following shouldChangeCharactersInRange task in your class.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   NSUInteger newLength = [textField.text length] + [string length] - range.length;
   return (newLength > 15) ? NO : YES;
}
gokhanakkurt
  • 4,935
  • 4
  • 28
  • 39
  • This is wrong as it will consider the length before the text field's text changes as a result of user typing and not what it would be. Check the question which has been marked as duplicate for more detail. – Deepak Danduprolu Jul 27 '11 at 16:52
2

Try this:

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

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

        if ([textFieldText length] > 15) 
        {
            return NO;
        }

 return YES;
}
Dax
  • 6,908
  • 5
  • 23
  • 30