-3

我在 Xcode 中打开了一个简单的 iPhone 项目。在情节提要文件中,我有一个视图控制器: 2 个文本字段 1 个标签 1 个圆形矩形按钮

我要做的是:让用户在字段 A 中输入任何数字,然后在字段 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

先感谢您!

4

1 回答 1

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)];
于 2013-07-05T17:57:25.503 回答