Defining legal input characters
I sometimes use a little trick to ensure that a UITextInputField only accepts a certain subset of characters. Say for example, you want to ensure that a user enters only letters and spaces. A UITextField delegate can catch each character as its typed and decide whether to add items to the active text field. Here's how.
Start by defining a legal set of characters. The following constant string includes the alphabet, both lower and upper case, plus the space character:
#define LEGAL @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "A simple delegate method can check whether a newly typed character belongs to that legal set. If so, it permits the text field to add it:
// allow only legal letters - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; }It's relatively easy to extend this concept to limit text input to well formed numbers. Start by using a number keyboard:
entryField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;Next, define two number sets: one with the period, one without.
#define NUMBERS @"0123456789" #define NUMBERSPERIOD @"0123456789."Finally, adjust the text field delegate method to check to see if a period has already been added. If so, the test reverts to the numbers only string:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *cs; NSString *filtered; // Check for period if ([entryField.text rangeOfString:@"."].location == NSNotFound) { cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet]; filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; } // Period is in use cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet]; filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; }It's pretty easy to see how you can extend this approach to allow for legal email addresses, user names, passwords and so forth. Just this small bit of code can save you a lot of overhead. You can avoid checking for legal entries and making users enter items again when you ensure that users can only enter legal values to begin with.
No comments:
Post a Comment