如何限制除点和下划线之外的UITextField中的特殊字符? 我已经尝试了下面的代码片段,但没有运气: #define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."- (BOOL)tex
我已经尝试了下面的代码片段,但没有运气:
#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; } }尝试下面给出的代码块,它对我来说很好.
SWIFT 3.0
let ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let cs = NSCharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted let filtered = string.components(separatedBy: cs).joined(separator: "") return (string == filtered) }
目标C.
#define ACCEPTABLE_CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_." - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; }
希望它也适合你.