计算循环中文本字段的输入

时间:2013-03-07 17:29:23

标签: xcode loops 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];
}  

我想在textfield2

中显示textfield1循环输入的TOTAL
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];  

2 个答案:

答案 0 :(得分:1)

实施UITextFieldDelegate协议,您可以在人员输入时从UITextField获取更新。当有人完成编辑文本字段时,textFieldDidEndEditing:会告诉您。

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

答案 1 :(得分:1)

可能需要修改代码:
在分配多个UITextField对象时,您需要将它们存储在这样的数组中。

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

稍后要做总计,你需要遍历数组并提取文本字段值并在这样的变量中累积。

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