限制多个UITextField的长度

时间:2011-05-29 22:27:29

标签: objective-c cocoa-touch ios uitextfield uitextfielddelegate

我有四个UITextField,并希望限制每个define MAXLENGTH 5 define MAXQTY 3 define MAXSIZE 4 define MAXBRAND 10 - (BOOL)textField:(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; } 的长度,但它们都是不同的长度。到目前为止,我有以下代码,但它不能正常工作

{{1}}

1 个答案:

答案 0 :(得分:2)

如果品牌,数量,尺寸和价格是实例变量(或属性)并连接到您的UITextFields,您可以尝试这样做:

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;
}