Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering characters entered into a UITextField

I have a UITextField in my application. I'd like to restrict the set of characters that can be can be entered into the field to a set that I have defined. I could filter the characters entered into the field when the text is committed using the UITextFieldDelegate method:

- (BOOL)textFieldShouldReturn:(UITextField*)textField

However, this gives the user a false impression as although restricted characters are removed from the final value, they were still visibly entered into the text field before pressing Return/Done/etc. What is the best approach that would prevent restricted characters appearing in the text field as they are selected on the keyboard?

Note: I am operating under the assumption that I have little control over which keys are provided by the iPhone keyboard(s). I am aware that I can switch between various keyboard implementations but am under the impression that I can't disable specific keys. This assumption may be incorrect.

like image 640
teabot Avatar asked Jun 18 '09 16:06

teabot


People also ask

What is UITextField for?

func textFieldDidEndEditing(UITextField) Tells the delegate when editing stops for the specified text field.

What is UITextField in Swift?

An object that displays an editable text area in your interface.

How do I know if my textfield is a first responder?

You could keep track of which text field is the first responder by either setting your view controller to be the delegate object of all text fields and then when your subclassed text fields gets the " becomeFirstResponder " method call, tell your view controller which text field is the current one.


2 Answers

Here is one of the cleanest approaches to restricting characters entered in a UITextField. This approach allows the use of multiple predefined NSCharacterSets.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowedCharacters formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
    [allowedCharacters formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];

    if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){

        return YES;

    }

    return NO;

}
like image 77
Brody Robertson Avatar answered Sep 21 '22 06:09

Brody Robertson


Look at textField:shouldChangeCharactersInRange

This method is called by the UITextFieldDelegate whenever new characters are typed or existing characters are deleted from the text field. You could return NO to not allow the change.

like image 39
marcc Avatar answered Sep 21 '22 06:09

marcc