使用UITextField限制只可输入中,英文,数字的方法
作者:辛多雷的挽歌
在我们日常开发中经常遇到一些情况,要UITextField只能输入某一种特定的字符.比如大写A-Z或者小写a-z,或者汉字.或者数字.那么该如何实现呢,下面通过这篇文章来看看吧。
前言
本文主要介绍使用UITextField
限制只可输入中,英文,数字,我们可以使用NSPredicate
正则表达式可以过滤,下面看看详细的步骤方法
首先设置UItextField的代理
实现如下方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if ([self isInputRuleAndNumber:string] || [string isEqualToString:@""]) { return YES; } return NO; }
然后添加事件,因为选择输入法联想的词.是不会经过textField:shouldChangeCharactersInRange:replacementString
:方法的
[textField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
实现:
- (void)textFieldChanged:(UITextField *)textField { NSString *toBeString = textField.text; NSString *lastString; if(toBeString.length>0) lastString=[toBeString substringFromIndex:toBeString.length-1]; if (![self isInputRuleAndNumber:toBeString]&&[self hasEmoji:lastString]) { textField.text = [self disable_emoji:toBeString]; return; } NSString *lang = [[textField textInputMode] primaryLanguage]; if([lang isEqualToString:@"zh-Hans"]) { UITextRange *selectedRange = [textField markedTextRange]; UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; if(!position) { NSString *getStr = [self getSubString:toBeString]; if(getStr && getStr.length > 0) { textField.text = getStr; } } } else{ NSString *getStr = [self getSubString:toBeString]; if(getStr && getStr.length > 0) { textField.text= getStr; } } }
再来实现限制:
pattern中,输入需要验证的通过的字符
小写a-z
大写A-Z
汉字\u4E00-\u9FA5
数字\u0030-\u0039
- (BOOL)isInputRuleAndNumber:(NSString *)str { NSString *pattern = @"[a-zA-Z\u4E00-\u9FA5\\u0030-\\u0039]"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; BOOL isMatch = [pred evaluateWithObject:str]; return isMatch; }
实现判断是否是Emoji
- (BOOL)hasEmoji:(NSString*)str{ NSString *pattern = @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; BOOL isMatch = [pred evaluateWithObject:str]; return isMatch; }
字符限制
#define kMaxLength 20; -(NSString *)getSubString:(NSString*)string { NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSData* data = [string dataUsingEncoding:encoding]; NSInteger length = [data length]; if (length > kMaxLength) { NSData *data1 = [data subdataWithRange:NSMakeRange(0, kMaxLength)]; NSString *content = [[NSString alloc] initWithData:data1 encoding:encoding]; if (!content || content.length == 0) { data1 = [data subdataWithRange:NSMakeRange(0, kMaxLength - 1)]; content = [[NSString alloc] initWithData:data1 encoding:encoding]; } return content; } return nil; }
总结
以上就是这篇文章的全部内容了,希望能对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。