Can I limit the character set for a UITextField?

依然范特西╮ 提交于 2019-12-08 08:17:03

问题


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.


回答1:


You could try using the following UITextFieldDelegate method:

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



回答2:


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];
}



回答3:


try using the UIKeyboardTypeNamePhonePad for your UITextField. It only has letters and numbers on it:

textField.keyboardType = UIKeyboardTypeNamePhonePad;



回答4:


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;
    }

}


来源:https://stackoverflow.com/questions/1863678/can-i-limit-the-character-set-for-a-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!