0

我有 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;
    } 
4

2 回答 2

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将包含选择/编辑的最后一个文本字段的标志

于 2013-05-14T12:36:18.500 回答
0

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

于 2013-05-14T12:37:54.917 回答