Xcode UITextField 限制字符类型 [英] Xcode UITextField limit type of characters
本文介绍了Xcode UITextField 限制字符类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Xcode中,如何用ABCD1234567"限制UITextField的字符,前4个字符是没有特殊字符的字母表,其余必须有6或7个数字.请帮我解决这个问题.感谢提前.
in Xcode, how can I limit the character of UITextField with "ABCD1234567", the first 4 chars is the alphabet with no special char and the rest must has 6 or 7 number. Please help me to solve this. Thanks for advance.
推荐答案
定义以下变量
#define NUMBERS @"0123456789"
#define ALPHABATES @"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
现在在文本字段的委托函数中,
Now in the delegate function of the textfield,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs;
NSString *filtered;
//for maximum characters
if (textField.text.length >= 11 && range.length == 0)
return NO;
if(textField.text.length<11)
{
NSString *cStr=[NSString stringWithFormat:@"%@%@",textField.text,string];
if([cStr length]<11)
{
if(range.location<4)
{
cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHABATES] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
else
{
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
}
else
{
int iPrevLength,iNextLength;
iPrevLength=[textField.text length];
iNextLength=11;
int iLengthDiff=iNextLength-iPrevLength;
string=[string substringToIndex:iLengthDiff];
if(range.location<4)
{
cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHABATES] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
else
{
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
if([string isEqualToString:filtered])
textField.text=[NSString stringWithFormat:@"%@%@",textField.text,string];
return NO;
}
}
return YES;
}
确保 ALPHABATES 有大写字母,所以它只适用于大写字母,如 A,B C 而不是 a,b,c....
Make sure as ALPHABATES has capital letters so it will only work for the caps letter like A,B C not a,b,c....
它首先接受 ALPHABATES 的 4 个字母,然后接受 NUMBERS 的 6-7 个字母.
It first accept the 4 letter of ALPHABATES then 6-7 letters of NUMBERS.
希望它对你有用.
告诉我.
这篇关于Xcode UITextField 限制字符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文