实时限制输入方法很多 我个人钟爱使用正则表达式 比较灵活简单
1 |
NSString * regex = @"(^[a-zA-Z0-9]$)"; 限制只能输入字母和数字 其他限制类型可以参考正则语法 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString * currentString = textField.text; // 删除回退的时候返回yes if (string.length == 0 && range.length == 1) { return YES; } if (textField == self.vin) { NSString * regex = @"(^[a-zA-Z0-9]$)"; NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [pred evaluateWithObject:string]; BOOL lessThanMax = [currentString length] < 17; return (isMatch && lessThanMax)?YES:NO; } if (textField == self.engineNo) { NSString * regex = @"(^[a-zA-Z0-9]$)"; NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [pred evaluateWithObject:string]; //BOOL lessThanMax = [currentString length] < 6; return isMatch?YES:NO; } return YES; } |
转载请注明:天狐博客 » NSPredicate正则进行TextField限制输入