Restrict UITextField size

5 Solutions Collect From Internet About “Restrict UITextField size”

Here is a code sample to limit the size of a UITextField:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  if ([[textField text] length] + [string length] - range.length > MAX_LENGTH) {
    return NO;
  } else {
    return YES; 

You could make your view controller conform to the UITextFieldDelegate protocol and implement textField:shouldChangeCharactersInRange:replacementString: – this is called whenever the user types a new character in the text field or deletes an existing character.

You can then check the character the user just entered for validity, returning NO for any invalid characters (like like +, = in your question).

There’s an example of this in this blog post.

This works for me.

-(BOOL)textFieldShouldReturn:(UITextField *)textField

    if([textField.text length]<=8){
    [tf resignFirstResponder];       
        return YES;
        return NO;

If you want to actively restrict the user from entering characters, what you’re going to want to do is set a delegate for the UITextField to handle events, and then look at the textDidChange notification. You can then look at the entered text every time it changes and if any undesired characters (or extra, beyond your desired limit) are entered, you can remove them.

See here for more info:

try using the UIKeyboardTypeNamePhonePad for your UITextField. It only has letters and numbers on it:

textField.keyboardType = UIKeyboardTypeNamePhonePad;