iOS限制输入解决方法

关于iOS 键盘输入限制(只能输入字母,数字,禁止输入特殊符号):

方法一: 直接限制输入

- (void)viewDidLoad {
    [super viewDidLoad];

    textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200, 30)];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.delegate = self;
    // 首先我们要设置一下键盘类型
    textField.keyboardType = UIKeyboardTypeASCIICapable;
    
    [self.view addSubview:textField];
}

// 直接不允许输入

- (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];
}

方法二: 使用正则表达式处理:

// 判断仅输入字母或数字:

- (BOOL) deptIdInputShouldAlphaNum: (NSString *)inputStr
{
    NSString *regex =@"[a-zA-Z0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:inputStr]) {
        return YES;
    }
    return NO;
}
原文地址:https://www.cnblogs.com/pengsi/p/6043945.html