Using shouldChangeCharactersInRange to limit typed characters, but cannot detect a return

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?

+4
source share
1 answer

It turns out that:

return represented by string of @"\n"

delete is represented by a string from @"" (with a range length that determines how many are deleted).

+7
source

Source: https://habr.com/ru/post/1382792/


All Articles