Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I did as marcc suggested and it worked well. Sample implementation follows.

Note: Variable names were selected for brevity and do not reflect my coding standards:

    ...
    myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"xyzXYZ"];
    ...
}

- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered {
    for (int i = 0; i < [textEntered length]; i++) {
        unichar c = [textEntered characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }
    return YES;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...