SoFunction
Updated on 2025-04-13

iOS keyboard input limit (only letters and numbers can be entered, and special symbols are prohibited)

First we need to set the keyboard type

= UIKeyboardTypeASCIICapable; (Set the keyboard according to personal preferences)

Then we want to set the textfield proxy <UITextFieldDelegate>

Set up the proxy and start writing the keyboard

Let's define a few macro definitions first

#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 which textfield, you can set the proxy for which textfield

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!