#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,weak) UITextField *num1Text;
@property (nonatomic,weak) UITextField *num2Text;
@property (nonatomic,weak) UILabel *resultLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//调用界面设置方法
[self setupUI];
}
//设置界面方法
#pragma mark -设置界面
- (void)setupUI{
//设置视图背景颜色
self.view.backgroundColor=[UIColor blackColor];
//实例化两个文本框
UITextField *num1Text=[[UITextField alloc] initWithFrame:CGRectMake(20, 40, 100, 40)];
UITextField *num2Text=[[UITextField alloc] initWithFrame:CGRectMake(150, 40, 100, 40)];
//设置两个文本框的背景颜色
num1Text.backgroundColor=[UIColor whiteColor];
num2Text.backgroundColor=[UIColor whiteColor];
//将两个文本框添加到根视图
[self.view addSubview:num1Text];
[self.view addSubview:num2Text];
//将两个文本框对象赋值给属性
_num1Text=num1Text;
_num2Text=num2Text;
//实例化三个Label对象
UILabel *plusLabel=[[UILabel alloc] initWithFrame:CGRectMake(130, 40, 40, 40)];
UILabel *equalLabel=[[UILabel alloc] initWithFrame:CGRectMake(260, 40, 40, 40)];
UILabel *resultLabel=[[UILabel alloc] initWithFrame:CGRectMake(310, 40, 40, 40)];
//给Label对象设置文本
plusLabel.text=@"+";
equalLabel.text=@"=";
resultLabel.text=@"result";
//给Label对象
[plusLabel setTextColor:[UIColor whiteColor]];
[equalLabel setTextColor:[UIColor whiteColor]];
[resultLabel setTextColor:[UIColor whiteColor]];
//设置边框大小自动按内容调整
[plusLabel sizeToFit];
[equalLabel sizeToFit];
[resultLabel sizeToFit];
//将label添加到根视图
[self.view addSubview:plusLabel];
[self.view addSubview:equalLabel];
[self.view addSubview:resultLabel];
//将计算结果的label赋值给对应属性
_resultLabel=resultLabel;
//实例化一个按钮
UIButton *calculate=[[UIButton alloc] initWithFrame:CGRectMake(200, 120, 50, 30)];
//设置按钮的名称和字的颜色
[calculate setTitle:@"计算" forState:UIControlStateNormal];
[calculate setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//设置按钮的背景颜色
[calculate setBackgroundColor:[UIColor whiteColor]];
//将按钮添加到根视图
[self.view addSubview:calculate];
//设置一个事件
[calculate addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
}
//计算方法
- (void)add{
//获取两个文本框的内容并转换为整型
NSInteger num1=[_num1Text.text intValue];
NSInteger num2=[_num2Text.text intValue ];
NSInteger result=num1+num2;
//将result封装成一个NSNumber类型的对象,调用它的description方法获得字符串赋值给结果Label
_resultLabel.text=@(result).description;
}
@end