检索一个字符串的长度的话:直接用 length,去进行判断就行了,
如果要检索字符串是否是自己要限制的类型的话,可以用正则表达式:
举个例子:
匹配9-15个由字母/数字组成的字符串的正则表达式:
NSString * regex = @"^[A-Za-z0-9]{9,15}$"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [pred evaluateWithObject:txtfldPhoneNumber.text];
如果只限制让输入中文和英文的话,可以这样设置:
NSString *regex = @"[a-zA-Zu4e00-u9fa5][a-zA-Zu4e00-u9fa5]+"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; if(![pred evaluateWithObject: _textField.text]) { //此动画为弹出 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"昵称只能由中文、字母组成" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil]; [alertView show]; return; }else { //代理方法的实现 [self.delegate sendName:_textField.text]; [self.navigationController popViewControllerAnimated:YES]; }
如果要单个限制的话,可以宏定义:
#define NUMBERS @"0123456789 " #define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" #define kAlpha @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" #define kNumber @"0123456789" #define kHans @"zh-Hans" #define HNMUBERS @"0123456789./*-+~!@#$%^&()_+-=,./;'[]{}:<>?`" 然后在-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 方法里面进行限制的操作: NSCharacterSet *cs; cs = [[NSCharacterSet characterSetWithCharactersInString:HNMUBERS]invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串 BOOL canChange = [string isEqualToString:filtered]; if(canChange) { [WYTools showTextOnlyHud:@"请输入英文或中文" delay:1.0]; return NO; } return YES;
替换不同的宏定义就可以了!