2013-07-05 14 views
-3

我有一個簡單的iPhone項目在Xcode中打開。 在故事板文件,我有一個視圖控制器: 2文本字段 1標籤 1圓矩形按鈕如何在Objective-C中創建簡單的添加?

我所試圖做的是以下幾點: 讓用戶在字段中的輸入任何數字,然後相同的字段B. 然後,一旦按下「提交」按鈕,我想應用程序添加這兩個值。

到目前爲止,這是我有的代碼,但我目前卡住,因爲我在構建上出現錯誤。

我的頭文件

#import <UIKit/UIKit.h> 



@interface ADDViewController : UIViewController 



@property (copy,nonatomic) NSString *valueA; 

@property (copy,nonatomic) NSString *valueB; 



@end 

我實現文件:

#import "ADDViewController.h" 



@interface ADDViewController() 

- (IBAction)submitButton:(id)sender; 

@property (weak, nonatomic) IBOutlet UITextField *numberA; 

@property (weak, nonatomic) IBOutlet UITextField *numberB; 

@property (weak, nonatomic) IBOutlet UILabel *answerLabel; 



@end 



@implementation ADDViewController 



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 

{ 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 

    if (self) { 

     // Custom initialization 

    } 

    return self; 

} 



- (void)viewDidLoad 

{ 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view. 

} 



- (void)didReceiveMemoryWarning 

{ 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 



- (IBAction)submitButton:(id)sender { 



    self.valueA = self.numberA.text; 

    self.valueB = self.numberB.text; 



// THE FOLLOWING IS WHERE I AM CURRENTLY GETTING AN ERROR WITH XCODE: 
// XCODE SAYS : INVALID OPERANDS TO BINARY EXPRESSION ('NSSTRING *' AND 'NSSTRING *') 

    NSString * total = self.valueA + self.valueB; 

} 

@end 

這是我的故事板文件的屏幕截圖:

http://i43.tinypic.com/352q98i.jpg

謝謝你提前!

回答

2

您必須將您的字符串轉換爲數字(例如,使用intValuefloatValue方法),添加這兩個數字,然後將生成的sum轉換回字符串。你不能對字符串本身進行數字操作。

你可以,因此,這樣做:

CGFloat a = [self.numberA.text floatValue]; 
CGFloat b = [self.numberB.text floatValue]; 
CGFloat sum = a + b; 
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
formatter.numberStyle = NSNumberFormatterDecimalStyle; 
self.answerLabel.text = [formatter stringFromNumber:@(sum)]; 
+1

我真的很感激,感謝羅布! – vzm