- (void)calculate {
float a;
if ([self.inputField.text isEqualToString:@"1in"]) a = 1.05f;
else if ([self.inputField.text isEqualToString:@"2in"]) a = 2.07f;
else if ([self.inputField.text isEqualToString:@"3in"]) a = 3.07f;
else a = 0.0f;
if (a) {
float b = a * ([self.inputField.text floatValue]);
self.inputField.text = [[NSString alloc] initWithFormat:@"%.2f", b];
}
else self.inputField.text = @"Invalid";
}
- (void)viewDidLoad
{
//...
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(10.0f, 20.0f, 300.0f, 30.0f)];
[self.inputField setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:self.inputField];
UIButton * doneButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, 55.0f, 300.0f, 30.0f)];
[doneButton setBackgroundColor:[UIColor blackColor]];
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(calculate) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:doneButton];
[doneButton release];
}
注:我更換了輸出格式%2.f
到%.2f
,因爲我想你可能需要這個格式。例如:
Input > 1in
Output< 1.05
Input > 2in
Output< 4.14
Input > 3in
Output< 9.21
我不明白你要做什麼,你的代碼示例沒有意義,並且語法不正確。你能再試一次嗎? – jrturton 2012-01-14 07:10:57