#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong)UITextField *num1TextField;
@property (nonatomic, strong)UITextField *num2TextField;
@property (nonatomic, strong)UILabel *resultLabel;
@property (nonatomic, strong)UILabel *addLabel;
@property (nonatomic, strong)UILabel *equalLabel;
@property (nonatomic, strong)UIButton *caculate;
@end
@implementation ViewController
#define kTextHeght 30
#define kTextWidth 100
#define kStartX 20
#define kStartY 50
#define kLabelWidth 30
#define kLabelHeight 30
- (void)viewDidLoad {
[super viewDidLoad];
//设置第一个文本输入框(第一
self.num1TextField = [[UITextField alloc] initWithFrame:CGRectMake(kStartX, kStartY, kTextWidth, kTextHeght)];
//self.num1TextField.backgroundColor = [UIColor redColor];
self.num1TextField.borderStyle = UITextBorderStyleRoundedRect;
self.num1TextField.keyboardType = UIKeyboardTypeNumberPad;
[self.view addSubview:_num1TextField];
//设置第二个文本输入框
self.num2TextField = [[UITextField alloc] initWithFrame:CGRectMake(kStartX + kTextWidth + 30, kStartY, kTextWidth, kTextHeght)];
//self.num1TextField.backgroundColor = [UIColor redColor];
self.num2TextField.borderStyle = UITextBorderStyleRoundedRect;
self.num2TextField.keyboardType = UIKeyboardTypeNumberPad;
[self.view addSubview:_num2TextField];
//设置第一个本文标签(加号)
self.addLabel = [[UILabel alloc] initWithFrame:CGRectMake(kStartX + kTextWidth, kStartY,kLabelWidth, kLabelHeight)];
self.addLabel.text = @"+";
self.addLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview: _addLabel];
//设置第二个文本标签(等号)
self.equalLabel = [[UILabel alloc] initWithFrame:CGRectMake(kStartX + kTextWidth * 2 + kLabelWidth, kStartY,kLabelWidth, kLabelHeight)];
self.equalLabel.text = @"=";
self.equalLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview: _equalLabel];
//设置第三个文本标签(现实结果)
self.resultLabel = [[UILabel alloc] initWithFrame:CGRectMake(kStartX + kTextWidth * 2 + kLabelWidth * 2, kStartY,kLabelWidth + 20, kLabelHeight)];
[self.view addSubview: _resultLabel];
//设置计算按钮
self.caculate = [[UIButton alloc] initWithFrame:CGRectMake(0, kStartY + kLabelHeight + 10, self.view.frame.size.width, kLabelHeight + 10)];
[self.caculate setTitle:@"计算" forState:UIControlStateNormal];
//设置按钮字体大小
_caculate.titleLabel.font = [UIFont systemFontOfSize: 14.0];
//设置按钮字体颜色
[self.caculate setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
[self.caculate setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
[self.view addSubview:_caculate];
[self.caculate addTarget:self action:@selector(Caculate) forControlEvents:UIControlEventTouchUpInside];
}
- (void) Caculate
{
NSString *num1 = self.num1TextField.text;
NSString *num2 = self.num2TextField.text;
int result = [num1 intValue] + [num2 intValue];
self.resultLabel.text = [NSString stringWithFormat:@"%d", result];
[self.view endEditing:YES];
}
@end
objective-c制作加法计算器
最新推荐文章于 2017-05-22 16:09:38 发布