3个文本框和一个计算按钮

时间:2013-05-14 12:30:55

标签: objective-c xcode4.6

我有3个文本框和一个计算按钮,如何判断按钮女巫文本框被选中并将数字转换为其他文本框,我已经标记了文本框1,2和3,我很新编程中的绿色,所以任何帮助都会很棒。 这是我的代码

- (IBAction)Calculate:(id)sender {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    float a = [[numberFormatter numberFromString:_Barrels.text] floatValue];
    float b = [[numberFormatter numberFromString:_Gallons.text] floatValue];
    float c = [[numberFormatter numberFromString:_Liters.text] floatValue];


    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", a];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", a * 42];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", a * 159];

    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", b * .0238];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", b];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", b * 3.785];

    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", c * .0063];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", c * .264];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", c];

    switch ([sender tag]) {
        case 1:
            [_Barrels resignFirstResponder];
            [_Gallons resignFirstResponder];
            [_Liters resignFirstResponder];
            break;
        default:
            break;
    } 

2 个答案:

答案 0 :(得分:1)

在ViewController.h文件中获取变量/标志以存储最后选择的文本字段

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
{
    int textfieldFlag;
}

@end
ViewController.m文件中的

实现textfieldDelegate方法

-(void)textFieldDidBeginEditing:(UITextField *)textField 
{     
    textfieldFlag=textField.tag;
}

然后在你的

 - (IBAction)Calculate:(id)sender
{
   //ABove Code....   

    if(textfieldFlag==1){
    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", a];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", a * 42];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", a * 159];
   }
if(textfieldFlag==2){
    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", b * .0238];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", b];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", b * 3.785];
   }
if(textfieldFlag==3){
    _Barrels.text = [[NSString alloc]initWithFormat:@"% .2f", c * .0063];
    _Gallons.text = [[NSString alloc]initWithFormat:@"% .2f", c * .264];
    _Liters.text = [[NSString alloc]initWithFormat:@"% .2f", c];
   }

   //Below Code...

}

相应地使用textfieldFlag

textfieldFlag将包含所选/编辑的最后一个文本字段的标记

答案 1 :(得分:0)

点击“计算”按钮时,必须调用此方法:- (void)textFieldDidEndEditing:(UITextField *)textField。在这里,通过检查tagValue来识别您编辑的文本字段,然后进行计算。确保添加文本字段的委托 - 否则 - (void)textFieldDidEndEditing将不会被调用。