Question

I have seen multiple approaches to this but cannot get this to work.

I am trying to restrict a text field to only allow alpha characters entered into it. I.e. ABCDEFabcdef (but all of them).

Here is my existing method:

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

    // Check for the back space/delete
    if (string.length <=0 ) {
        if ([self.wordArray lastObject]) {
            [self.wordArray removeObjectsInRange:range];
            [self.tileCollectionView reloadData];
            return YES;

        }
    }

    // Check to make sure the word is not above 16 characters, that should be enough right?
    if (textField.text.length >= 16 ) {
        NSLog(@"WOOO SLOW DOWN THE TEXT IS ABOVE 16");
        return NO;
    } else {
            [self.wordArray addObject:string];
            [self.tileCollectionView reloadData];
            return YES;
    }

}

At present I check for a back space and remove the last entry from an Array. Also if the letter is accepted then I add the letter as an object to an array, that is for something else. But the logic for the ALPHA check should also take this into account, only if the letter is 'legal' should it add to the array and reload the collection view.

Was it helpful?

Solution

Well, one way you could do it would be to create your own character set to compare against. Then you can take advantage of NSString's stringByTrimmingCharactersInSet: and NSCharacterSet's invertedSet property to remove all characters from the set that don't match the characters you initially specify. Then, if the final string matches the input string, it didn't contain illegal characters.

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];

NSString *input = @"a";

NSString *output = [input stringByTrimmingCharactersInSet:[myCharSet invertedSet]];

BOOL isValid = [input isEqualToString:output];

NSLog(@"%d",isValid);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top