Wednesday, March 25, 2009

Limiting Text Field Input

Received a question today about how to make a UITextField so that it can only accept a certain number of characters of input. Say, you wanted a text field that only allows up to five characters to be entered, and then accepts no more. It's actually easy.

First step is to set your controller (or other appropriate class) as the text field's delegate. You should conform that class to the UITextFieldDelegate protocol, and then do something like this:
myTextField.delegate = self
You can also set the delegate in Interface Builder by control-dragging from the text field to File's Owner or some other object instance, and selecting the delegate outlet.

After that, you just need to implement a delegate method to limit the input.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 5);
}


You can replace "5" with whatever value, variable, or constant is appropriate for your situation. Whenever we return NO from this delegate method, the pending edit is cancelled.

No comments:

Post a Comment