仅允许UITextField使用字母数字字符 [英] Allow only alphanumeric characters for a UITextField
问题描述
如何在iOS UITextField
中仅允许输入字母数字字符?
How would I go about allowing inputting only alphanumeric characters in an iOS UITextField
?
推荐答案
使用UITextFieldDelegate方法 -textField:shouldChangeCharactersInRange:replacementString:
,其中NSCharacterSet包含您要允许的字符的反转。例如:
Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString:
with an NSCharacterSet containing the inverse of the characters you want to allow. For example:
// in -init, -initWithNibName:bundle:, or similar
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
// in -dealloc
[blockedCharacters release];
请注意,您需要声明您的类实现了协议(即 @interface MyClass:SomeSuperclass< UITextFieldDelegate>
)并将文本字段的委托
设置为您班级的实例。
Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass <UITextFieldDelegate>
) and set the text field’s delegate
to the instance of your class.
这篇关于仅允许UITextField使用字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!