2012-01-14 74 views
1

新的objective-c和我只是找不到這個問題的答案在任何地方。我正在運行IBAction進行計算,但我需要來自標籤的輸入來實際上等於方程中的其他內容。IBAction浮動,具有相同的不同數字,具體取決於輸入

例如:

-(IBAction)calculate; { 
    float a = 1.05 if ([label1.text] == 1in); 
     a = 2.07 if ([label1.text] == 2in); 
     a = 3.07 if ([label1.text] == 3in); 
    float b = a*([textField1.text floatValue]); 
     label2.text = [[NSString alloc] initWithFormat:@"%2.f", b]; 
    } 

我知道我不是甚至接近得到它的權利,但我希望你的想法是什麼,我要找的。

謝謝!

+1

我不明白你要做什麼,你的代碼示例沒有意義,並且語法不正確。你能再試一次嗎? – jrturton 2012-01-14 07:10:57

回答

0
- (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 
+0

謝謝! Kjuly!完美的作品! – user1148954 2012-01-14 12:31:31

+0

@ user1148954不客氣:) – Kjuly 2012-01-14 12:34:43

相關問題