0

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

1 に答える 1

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;
}
于 2011-05-29T23:22:57.297 に答える