更新时间:2023-02-21 09:36:24
定义以下变量
#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.
希望它对你有用.
告诉我.