»
S
I
D
E
B
A
R
«
iPhone SDK: How To Set Max Character length in UITextField
May 14th, 2009 by Anish Kumar

We can use the UITextField’s delegate method

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

to set the maximum character length.

This can be done by doing the following:

#define MAX_LENGTH 10

- (BOOL)textField: (UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string
{
    if (textField.text.length >= MAX_LENGTH && range.length == 0)
    {
        return NO; 
    }
    else
    {
        return YES;
    }
}
About Me: Anish:
Mac OS X software development is my bread winner with over 6 years of experience. Expertise in Color Management, TWAIN Scanner drivers on Mac OS X, Photoshop Filter and Import Plugin development on Mac OS X, iPhone. As an hobby I love to work on PHP, Flex, AIR, Photoshop. Check the 'About' page for more.

2 Responses  
srinivas writes:
November 12th, 2009 at 11:39 am

how this method is called. my text field name is sampleText. Where i need to change this code. And i am developing calculator application.So i want to limit the text field. And please some code about where i need to write delegate and how can i call this method.

thanks in advance.

Evandro writes:
February 8th, 2010 at 5:42 pm

Hi!!

I have a one question: If the user paste one string ?
When type no problem. But if the data that is paste have more lenght than maxsize. have problem

Leave a Reply

Spam protection by WP Captcha-Free