Limit UITextField Size

How to limit the number of characters in a UITextField?

I. If I limit it to 10 characters, the user will not be able to enter more than 10. Also, I want him not to enter some special characters, such as +, =, etc.

How can I do it?

+4
source share
5 answers

Here is a sample code 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; } } 
+10
source

You can configure your display controller on the UITextFieldDelegate protocol and implement textField:shouldChangeCharactersInRange:replacementString: - this is called whenever a user enters a new character in a text field or deletes an existing character.

Then you can check the character entered by the user for validity only by returning NO for any invalid characters (e.g. like +, = in your question).

Here is an example of this in this post.

+7
source

This works for me.

 -(BOOL)textFieldShouldReturn:(UITextField *)textField { if([textField.text length]<=8){ [tf resignFirstResponder]; return YES; } else return NO; } 
+2
source

If you want to actively prohibit the user from entering characters, then you need to set a delegate for UITextField to handle events, and then view the textDidChange notification. You can then view the entered text every time it changes, and if any unwanted characters (or additional characters that exceed your desired limit) are entered, you can delete them.

See here for more information: http://discussions.apple.com/thread.jspa?messageID=6971952

+1
source

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

 textField.keyboardType = UIKeyboardTypeNamePhonePad; 
0
source

All Articles