Set Maximum Length of String in UITextField

September 3, 2010

This is actually pretty simple to do. First off I would make sure you tell your Application you want to make use of the UITextFieldDelegate functions otherwise it won’t work. To do that simply Append <UITextFieldDeletegate> to your header file, here’s an example of how to do that:

sample.h:

[php]@interface SampleViewController : UIViewController <UITextFieldDelegate> {

}
@end[/php]

After that is done edit your sample.m file and add these lines:

[php]-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] – range.length;
return (newLength > 8) ? NO : YES;
}[/php]

What this does is makes a count of how many characters are there and returns YES if the length is less than 8 characters, or a NO if it is greater than 8 characters. You can make this limit anything you want.

+1 this post if it helped you!

Leave a Reply