Limit the length of multiple UITextFields
I have four UITextField
s, and would like to limit the length of each one, but they are all different lengths. I have the following code so far, but it doesn't quite work correctly
define MAXLENGTH 5
define MAXQTY 3
define MAXSIZE 4
define MAXBRAND 10
- (BOOL)textFiel开发者_运维百科d:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int lengtha = [brand.text length] ;
NSLog(@"lenghta = %d",lengtha);
if (lengtha >= MAXBRAND && ![string isEqualToString:@""]) {
brand.text = [brand.text substringToIndex:MAXBRAND];
return NO;
}
return YES;
int lengthb = [qty.text length] ;
NSLog(@"lenghtb = %d",lengtha);
if (lengthb >= MAXQTY && ![string isEqualToString:@""]) {
qty.text = [qty.text substringToIndex:MAXQTY];
return NO;
}
return YES;
int lengthc = [size.text length] ;
NSLog(@"lenghtc = %d",lengtha);
if (lengthc >= MAXSIZE && ![string isEqualToString:@""]) {
size.text = [size.text substringToIndex:MAXSIZE];
return NO;
}
return YES;
int lengthd = [price.text length] ;
NSLog(@"lenghtd = %d",lengtha);
if (lengthd >= MAXLENGTH && ![string isEqualToString:@""]) {
price.text = [price.text substringToIndex:MAXLENGTH];
return NO;
}
return YES;
}
If brand, qty, size and price are instance variables (or properties) and are connected to your UITextFields you could try this:
define MAXLENGTH 5
define MAXQTY 3
define MAXSIZE 4
define MAXBRAND 10
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == brand) {
int lengtha = [brand.text length];
NSLog(@"lenghta = %d",lengtha);
if (lengtha >= MAXBRAND && ![string isEqualToString:@""]) {
brand.text = [brand.text substringToIndex:MAXBRAND];
return NO;
}
return YES;
} else if (textField == qty) {
int lengthb = [qty.text length];
NSLog(@"lenghtb = %d",lengthb);
if (lengthb >= MAXQTY && ![string isEqualToString:@""]) {
qty.text = [qty.text substringToIndex:MAXQTY];
return NO;
}
return YES;
} else if (textField == size) {
int lengthc = [size.text length];
NSLog(@"lenghtc = %d",lengthc);
if (lengthc >= MAXSIZE && ![string isEqualToString:@""]) {
size.text = [size.text substringToIndex:MAXSIZE];
return NO;
}
return YES;
} else if (textField == price) {
int lengthd = [price.text length];
NSLog(@"lenghtd = %d",lengthd);
if (lengthd >= MAXLENGTH && ![string isEqualToString:@""]) {
price.text = [price.text substringToIndex:MAXLENGTH];
return NO;
}
return YES;
}
return YES;
}
精彩评论