Question

In my iOS application, I have a UITextField that presently limits its character entry to 50 characters, and when it receives a single character, it enables a UIButton. What I am trying to do now is ensure that the user can only enter alphanumeric characters as well, but this is where I am having trouble. Here is the code that I have thus far:

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

BOOL canEdit=NO;
    NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet];
    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if (newLength > 0) {

        for (int i = 0; i < [string length]; i++)
        {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c])
            {
                canEdit=NO;
                self.myButton.enabled = NO;
            }
            else
            {
                canEdit=YES;
                self.myButton.enabled = YES;
            }
        }

    }  else  self.myButton.enabled = NO;


    return (newLength > 50 && canEdit) ? NO : YES;
}

Originally, my code was just limiting the character entry to just 50 characters, and enabling my button looked like the following:

NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if (newLength > 0) self.doneButton.enabled = YES;
    else self.doneButton.enabled = NO;

    return (newLength > 45) ? NO : YES;

The point I want to make is that I want to incorporate the limitation of alphanumeric characters within my existing code, and not replace it. This is the challenging part for me.

Was it helpful?

Solution

You will need to loop through and return NO to the method when the character is a non-alphanumeric one. So, the code that you have should be like:

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

    BOOL canEdit=NO;
    NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }
    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if (newLength > 0) {

        for (int i = 0; i < [string length]; i++)
        {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c])
            {
                canEdit=NO;
                self.myButton.enabled = NO;
            }
            else
            {
                canEdit=YES;
                self.myButton.enabled = YES;
            }
        }

    }  else  self.myButton.enabled = NO;


    return (newLength > 50 && canEdit) ? NO : YES;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top