NSCharacterSet: how to add "_" to alphanumeric text?

Create an NSCharacter set to restrict the UITextField for entering user names. I want the user to also be able to enter an underscore (therefore [A-Za-z0-9_]), but alphanumericCharacterSet does not include it. Is there a way to indicate such a range in short form? I see + (id)characterSetWithRange:(NSRange)aRange , but I don’t understand how this will work.

I have a simple subclass of the UITextField class to which I pass a character set. The restriction works fine and does not allow the user to enter anything other than alphanumeric. Just add "_" to these discounts.

 NSCharacterSet *characterSet = [NSCharacterSet alphanumericCharacterSet]; [textField setAllowed:characterSet]; [textField setFrame:frame]; 
+54
objective-c iphone nscharacterset
May 04 '10 at 17:49
source share
3 answers
 NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"]; [_alnum formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]]; 
+114
May 04 '10 at 17:59
source share

Another way would be to make it mutable and add it.

 NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet]; [characterSet addCharactersInString:@"_"]; 
+28
Mar 15 '12 at 5:05
source share
 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *blockedCharacters = [[NSCharacterSet whitespaceCharacterSet] invertedSet]; NSCharacterSet *blockedCharacters2 = [[NSCharacterSet letterCharacterSet] invertedSet]; return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound || [string rangeOfCharacterFromSet:blockedCharacters2].location); } 
0
Jan 13 '15 at 21:37
source share



All Articles