我在Xcode中打开了一个简单的iPhone项目。 在storyboard文件中,我有一个视图控制器: 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
提前谢谢!
答案 0 :(得分:2)
您必须将字符串转换为数字(例如,使用intValue
或floatValue
方法),添加这两个数字,然后将生成的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)];