使用UITextField限制只可输入中,英文,数字的方法
程序员文章站
2023-12-19 10:31:10
前言
本文主要介绍使用uitextfield限制只可输入中,英文,数字,我们可以使用nspredicate正则表达式可以过滤,下面看看详细的步骤方法
首先设置uitex...
前言
本文主要介绍使用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; }
总结
以上就是这篇文章的全部内容了,希望能对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。