一.项目要求:制作一个加法计算器。在第1个和第2个文本框中输入两个整数,然后点击“计算”按钮,可将计算结果显示在第3个文本框中。
二.开发步骤:
1.搭建UI界面
2.监听按钮的点击事件
3.获取文本框的内容
4.将计算的结果显示到文本标签中
三.开发细节:
1.打开Xcode,新建一个project,Product Name写:加法计算器,Language选择:Objective-C,Devices选择:iphone。
2.新建完成后,点击Main.storyboard文件,将在上面搭建UI界面,将所需的相关控件拖到相应位置。
3.编写代码。
//ViewController.h文件(声明文件) #import <UIKit/UIKit.h> @interface ViewController : UIViewController //申明一个方法来监听按钮点击 - (IBAction)btnClick; //声明两个属性用来保存文本输入框 @property (nonatomic,weak) IBOutlet UITextField *num1; @property (nonatomic,weak) IBOutlet UITextField *num2; @property (nonatomic,weak) IBOutlet UILabel *result; @end
//ViewController.m 文件(实现文件): #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark 监听按钮点击事件 -(void)btnClick{ //获取文本框中的文字 NSString *text1 = self.num1.text; NSString *text2 = self.num2.text; //将文字转换为数字 int i1 = [text1 intValue]; int i2 = [text2 intValue]; //将两个数字之和显示到result标签 self.result.text = [NSString stringWithFormat:@"%d",i1+i2]; } @end