Krodak
Krodak

Reputation: 1493

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

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 character 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:

Thank You in advance for any help :)

Upvotes: 0

Views: 317

Answers (2)

user523234
user523234

Reputation: 14834

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

Upvotes: 0

omz
omz

Reputation: 53551

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

Upvotes: 1

Related Questions