问题
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.
回答1:
Define the following variables
#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;
}
Make sure as ALPHABATES has capital letters so it will only work for the caps letter like A,B C not a,b,c....
It first accept the 4 letter of ALPHABATES then 6-7 letters of NUMBERS.
I hope it will work for you.
Let me know.
回答2:
//this method is delegate method of UITextField
- (void)textFieldDidEndEditing:(UITextField *)textField
{
int strLen = [textField.text length];
BOOL invalidChar=FALSE;
if (strLen<=11)
{
for (int i=0,j=1;i<strLen;i++,j++)
{
char strChar = [textField.text characterAtIndex:i];
if (j<=4)
{
if (strChar<65 || strChar>90)
{
invalidChar=TRUE;
break;
}
}
if (j>=5)
{
if (strChar<48 || strChar>57)
{
invalidChar=TRUE;
break;
}
}
}
}
else
{
[txtString becomeFirstResponder];
}
if (invalidChar)
{
[txtString becomeFirstResponder];
}
}
来源:https://stackoverflow.com/questions/22471468/xcode-uitextfield-limit-type-of-characters