iOS keyboard input limits of can only input letters and numbers and special symbols are prohibited

  • 2021-12-11 19:14:08
  • OfStack

First, we need to set the keyboard type under 1

textFiled.keyboardType = UIKeyboardTypeASCIICapable;  (Set keyboard according to personal preference)

Then we will set up the proxy for textfield < UITextFieldDelegate >

Set up the agent and start writing the keyboard

First, define several macro definitions


#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

Then write the proxy method


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
  NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
  return [string isEqualToString:filtered];
}

Note: If you need to set the keyboard for any textfield, you can set the proxy for any textfield


Related articles: