怎麼限制UITextField 中的特殊字符?只保留點和下劃線。我用了下面的代碼,但是沒有反應:
#define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1){
NSLog(@"not allowed");
return NO;
}
else{
return YES;
}
}
我想了好半天,不知道怎麼回答好...因為方法太多了...
方法一: 使用scaner(如果你堅持要自定義accetpable的字符)
NSString *yourString = @"tBe47s_-#h54df";
NSMutableString *resultString = [NSMutableString stringWithCapacity:yourString.length];
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."];
while ([scanner isAtEnd] == NO)
{
NSString *buffer;
if ([scanner scanCharactersFromSet:charSet intoString:&buffer])
[resultString appendString:buffer];
else
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
NSLog(@"result: %@", resultString);
方法二:正則表達式(iOS4.0以後適用,4之前要用第三方庫)
NSString *yourString = @"tBe%#&4.7s_-#h5S4df";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"([^A-Za-z0-9_.])"
options:0
error:&error];
NSString *resString = [regex stringByReplacingMatchesInString:yourString options:0 range:NSMakeRange(0, yourString.length) withTemplate:@""];
NSLog(@"result: %@", resString);