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

北慕城南 提交于 2019-12-02 19:56:05
drawnonward

Objective-C

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

Swift

let _alnum = NSMutableCharacterSet(charactersIn: "_")
_alnum.formUnion(with: .alphanumerics)

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
AsbelK
- (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);  

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!