views:

1001

answers:

2

How can I limit the number of characters in a UITextField?

I.e if I limit it to 10 characters, the user will be unable to enter more than 10. Also I want to prevent him from entering some special characters like +, =, etc.

How would I do this?

+1  A: 

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: http://discussions.apple.com/thread.jspa?messageID=6971952

Amber
I don't think there is a textDidChange notification in the UITextFieldDelegate
marcc
+2  A: 

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.

Chu Yeow