开发者

How to access character typed by user before showing it in UITextField

开发者 https://www.devze.com 2023-04-11 10:40 出处:网络
I\'m writing application in which I need to validate text entered by user to UITextField, char by char with some method.

I'm writing application in which I need to validate text entered by user to UITextField, char by char with some method.

The difficult thing is that client wants to do all the validation before user see charac开发者_开发问答ter in the UITextField because there might be situation that his server application doesn't support '$' sign, so in my validation method I should replace it with 'USD' string - and he doesn't want user to see '$', just 'USD' immediately.

I know about events like UIControlEventEditingChanged etc., but still, I don't know 2 things:

  • how to access character typed by user before it's seen in UITextField and execute validation there

  • how to subtitute this character 'on the fly' and put it manually to UITextField (but I suppose I'll just append this to [[textField] text] NSString

Thank You in advance for any help :)


Implement the UITextFieldDelegate method textField:shouldChangeCharactersInRange:replacementString:, e.g.:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL validated = ...; //do your validation
    return validated;
}


Similar to omz's answer but more complete code if you need:

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

    NSString *filtered;
    filtered = [string stringByReplacingOccurrencesOfString:@"$" withString:@"USD"];

    //optionally if you want to only have alphanumeric characters
    //NSMutableCharacterSet *mcs1 = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];  //only alphabet character
    //[mcs1 removeCharactersInString:@"0123456789"];  
    //filtered = [[filtered componentsSeparatedByCharactersInSet:mcs1] componentsJoinedByString:@""];
    //release mcs1;

    return [string isEqualToString:filtered];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号