NSCharacterSet: How do I add “_” to alphanumericCharacterSet text restriction?

前端 未结 3 675
感情败类
感情败类 2021-02-02 05:28

Building an NSCharacter set to restrict a UITextField for entering user names. I want the user to be able to also enter an underscore (so [A-Za-z0-9_]) but alphanumericCharacter

相关标签:
3条回答
  • 2021-02-02 05:56
    - (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 讨论(0)
  • 2021-02-02 06:06

    Another way would have been to make it mutable and add it.

    Objective-C

    NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];
    [characterSet addCharactersInString:@"_"];
    

    Swift

    let characterSet = NSMutableCharacterSet.alphanumeric()
    characterSet.addCharacters(in: "_")
    

    You could verify it has been added (in a Playground) with:

    characterSet.characterIsMember(UInt16(Character("^").unicodeScalars.first!.value)) // false
    characterSet.characterIsMember(UInt16(Character("_").unicodeScalars.first!.value)) // true -- YAY!
    characterSet.characterIsMember(UInt16(Character("`").unicodeScalars.first!.value)) // false
    
    0 讨论(0)
  • 2021-02-02 06:07

    Objective-C

    NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
    [_alnum formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    

    Swift

    let _alnum = NSMutableCharacterSet(charactersIn: "_")
    _alnum.formUnion(with: .alphanumerics)
    
    0 讨论(0)
提交回复
热议问题