我有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;
}
在ViewController.h文件中取一个变量/flag来存储最后选择的文本字段
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
{
int textfieldFlag;
}
@end
在ViewController中。m文件实现textfieldDelegate方法
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
textfieldFlag=textField.tag;
}
then in ur
- (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
将包含选定/编辑的最后一个文本字段的标志
当您点击计算按钮时,必须调用此方法:- (void)textFieldDidEndEditing:(UITextField *)textField
。在这里,通过检查tagValue来确定您编辑了哪个文本字段,并据此进行计算。请确保添加文本字段的委托,否则- (void)textFieldDidEndEditing将不会被调用