Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using shouldChangeCharactersInRange to limit characters entered, but cannot detect return

Tags:

ios

ios5

I'm using the following code in my UITextField delegate to limit the characters that can be entered:

FYI: The UITextField outlet is called nameChoiceField. Plus there is a label outlet called errorMessageLabel.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSString *potentialNewChosenName = [self.nameChoiceField.text stringByReplacingCharactersInRange:range withString:string];

    NSCharacterSet *nonLettersNumbersOrDashes = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- "] invertedSet];

    if ([potentialNewChosenName stringByTrimmingCharactersInSet:nonLettersNumbersOrDashes].length != potentialNewChosenName.length) {
        self.errorMessageLabel.text = @"Only letters, numbers etc allowed.";
        return NO;
    } else {
        self.errorMessageLabel.text = @"That's okay.";
        return YES;
    }
}

Which works nicely (so long as autocorrect is off, and if you add some other stuff in to stop the auto full stop after you enter 2 spaces).

However! When you tap return on the keyboard, it doesn't allow it (displaying the error message "Only letters....").


How do you restrict the input a user can make, and still have the return button to be recognised?

Also, are there any best practices for recognising the delete button that should be implemented above?

like image 398
Jon Cox Avatar asked Feb 23 '23 07:02

Jon Cox


1 Answers

Turns out that:

return is represented by a string of @"\n"

delete is represented by a string of @"" (with the length of the range determining how much gets deleted).

like image 80
Jon Cox Avatar answered May 17 '23 07:05

Jon Cox