iPhone – Set Maximum Length of String in UITextField

There is no maximum length attribute in the UITextField. Here is a work around to limit the number of input characters in an UITextField.

1. Implement the UITextFieldDelegate in the .h header file

...
@interface HelloViewController : UIViewController <UITextFieldDelegate> {
	...
}
@end

 

2. Implement this function in the .m implementation file to set the maximum length to 4 characters

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

 

Done =)

Reference: iPhone SDK: Set Max Character length TextField

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.