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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With