I use the following code in my UITextField to limit the characters that can be entered:
FYI: The output of a UITextField
is called nameChoiceField
. In addition, there is a tag removal 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 okay."; return YES; } }
Which works well (as long as auto-correction is turned off, and if you add some other material to stop the automatic full stop after entering two spaces).
But! When you press return
on the keyboard, it does not allow it (it displays the error message "Only letters ....").
How do you limit the input that the user can do and still have a return
button for recognition?
Also, are there any recommendations for recognizing the delete
button, which should be implemented above?
source share