Can I limit the character set for a UITextField?
-
16-09-2019 - |
Question
I have a bitmap font which which doesn't have every single character, such as accented characters (é î ü etc) or symbols such as "¥" or © which I'm using to display usernames in a Highscore table for a game.
Is it possible to limit the UIKit keyboard to certain characters, or only allow certain characters in the UITextField? Or will I have to roll my own input mechanism? I'm thinking and old school, Arcade style, one letter at a time "thing" would be ok.
Solution
You could try using the following UITextFieldDelegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
OTHER TIPS
Using the UITextFieldDelegate method mentioned by intregus, you can do this quite easily:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Only characters in the NSCharacterSet you choose will insertable.
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
try using the UIKeyboardTypeNamePhonePad
for your UITextField
. It only has letters and numbers on it:
textField.keyboardType = UIKeyboardTypeNamePhonePad;
Using Interface builder you can link and get the event for "Editing changed" in any of your function. Now there you can put check for the length
- (IBAction)onValueChange:(id)sender
{
NSString *text = nil;
int MAX_LENGTH = 20;
switch ([sender tag] )
{
case 1:
{
text = myEditField.text;
if (MAX_LENGTH < [text length]) {
myEditField.text = [text substringToIndex:MAX_LENGTH];
}
}
break;
default:
break;
}
}