user2110381
user2110381

Reputation: 11

Calculate input from textfield in a loop

How can I calculate a textfield in a loop? I have a textfield in a loop and I want to calculate the input in another textfield.

x = 36;     y = 0;   w = 36      h = 25 ;

moretext = 0 ;

for (moretext=0; moretext<5; moretext ++) {
    textFiled1 = [[UITextField alloc]initWithFrame:CGRectMake(x, y, w, h)];
    textFiled1.textAlignment = NSTextAlignmentCenter;
    textFiled1.backgroundColor = [UIColor clearColor];
    textFiled1.font = [UIFont fontWithName:@"Helvetica " size:(8)];
    x+=36 ;

    [self.view addSubview:textFiled1];
}  

I want to have the TOTAL for the textfield1 loop input showing in textfield2

textFiled2 = [[UITextField alloc]initWithFrame:CGRectMake(180, 0, 36, 25)];
textFiled2.textAlignment = NSTextAlignmentCenter;
textFiled2.backgroundColor = [UIColor clearColor];
textFiled2.font = [UIFont fontWithName:@"Helvetica " size:(8)];

[self.view addSubview:textFiled2];  

Upvotes: 1

Views: 551

Answers (2)

Deepak Keswani
Deepak Keswani

Reputation: 117

May be you need to revise the code:
At the time of allocating multiple UITextField objects, you need to store these in some array like this.

myArray  = [[NSMutableArray alloc]init];
UITextField *textFiled1;

int moretext = 0 ;

for (moretext=0; moretext<5; moretext ++, y=y+50) {
    textFiled1 = [[UITextField alloc]initWithFrame:CGRectMake(x, y, w, h)];
    textFiled1.textAlignment = NSTextAlignmentCenter;
    textFiled1.backgroundColor = [UIColor blueColor];
    textFiled1.font = [UIFont fontWithName:@"Helvetica " size:(8)];
    textFiled1.text = [NSString stringWithFormat:@"%d",y];
    //x+=36 ;
    [myArray addObject:textFiled1];
    [self.view addSubview:textFiled1];
    NSLog(@"view Did Load called");
}

Later to do the total you need to traverse through array and extract the text field value and accumulate in some variable like this.

- (int) calc {
int total=0;
int counter;
for (counter=0; counter<5; counter ++) {
    UITextField *field1 = [myArray objectAtIndex:counter];
    total = total + [field1.text intValue];
    NSLog(@"value: %d",[field1.text intValue]);

}

return total;
}

Upvotes: 1

Richard Brown
Richard Brown

Reputation: 11444

Implementing the UITextFieldDelegate protocol you can get updates from the UITextField as people type. textFieldDidEndEditing: will tell you when someone is done editing a textfield as well.

See: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

Upvotes: 1

Related Questions