我在Xcode中打开了一个简单的iPhone项目。在情节提要文件中,我有一个带有以下内容的视图控制器:2个文本字段1个标签1个圆形rect按钮
我要执行的操作如下:让用户在字段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
先感谢您!
您必须将字符串转换为数字(例如使用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)];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句