在 UITextView 中只允许字母数字字符 [英] Allow only alpha numeric characters in UITextView
本文介绍了在 UITextView 中只允许字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论如何我可以允许用户在文本视图中只输入字母数字字符而不能输入其他字符.
Is there anyway i can allow user to enter only alpha numeric characters in a text view and no other character.
尝试过,
if ([_txtView.text rangeOfCharacterFromSet:alphaSet].location != NSNotFound)
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"Only alpha numeric characters are allowed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}
但这仅适用于某些时候
谢谢!!
推荐答案
您可以使用 [[[NSCharacterSet alphanumericCharacterSet] reverseSet] 来实现.此方法将返回一个仅包含接收器中不存在的字符的字符集.
You can achieve that using [[[NSCharacterSet alphanumericCharacterSet] invertedSet]. This method will return a character set containing only characters that don’t exist in the receiver.
NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
//符合 UITextField 委托并实现该方法.
//Conform UITextField delegate and implement this method.
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
}
这篇关于在 UITextView 中只允许字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文