NSCharacterSet:如何添加“_” to alphanumericCharacterSet文本限制? [英] NSCharacterSet: How do I add "_" to alphanumericCharacterSet text restriction?

查看:196
本文介绍了NSCharacterSet:如何添加“_” to alphanumericCharacterSet文本限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建NSCharacter集以限制UITextField以输入用户名。我希望用户能够输入下划线(所以[A-Za-z0-9_]),但alphanumericCharacterSet不包含它。有没有办法在短格式中指定类似的范围?我看到 +(id)characterSetWithRange:(NSRange)aRange ,但我真的不明白它是如何工作的。

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 alphanumericCharacterSet does not include it. Is there a way to specify a range like that in short form? I see + (id)characterSetWithRange:(NSRange)aRange, but I'm not really understanding how that would work.

我有一个简单的UITextField子类,我将字符集传递给。限制工作正常,不允许用户输入除字母数字之外的任何内容。只需要在这些限额中添加_。

I've got a simple UITextField sub-class that I pass the character set to. The restriction works fine and doesn't allow the user to enter anything but alpha numeric. Just need to add the "_" to those allowances.

NSCharacterSet *characterSet = [NSCharacterSet alphanumericCharacterSet];
[textField setAllowed:characterSet];
[textField setFrame:frame];


推荐答案

Objective-C

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

Swift

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

这篇关于NSCharacterSet:如何添加“_” to alphanumericCharacterSet文本限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆