做一個計算機是 iOS 入門的經典練習——它同時涵蓋了視圖建立、按鈕事件綁定、字串處理與基本型別轉換。以下完整實作,支援 1~9、0、小數點、四則運算、等號、全部清除與逐位刪除。
版面規劃如下:
#import "ZKJAppDelegate.h" @interface ZKJAppDelegate () @property (retain, nonatomic) UIView *containView; @property (retain, nonatomic) UIButton *button; @property (retain, nonatomic) UILabel *label; @property (retain, nonatomic) NSMutableString *string; // 保存輸入的字元 @property (assign, nonatomic) double num1, num2, num3, num4; // num1:保存輸入的數值 // num2:保存運算前的數值 // num3:運算結果 // num4:判斷要進行哪一種運算(1=+ 2=- 3=* 4=/) @end
@implementation ZKJAppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.containView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
self.containView.backgroundColor = [UIColor clearColor];
[self.window addSubview:self.containView];
// ── 顯示區 ──
self.label = [[UILabel alloc] initWithFrame:CGRectMake(30, 40, 190, 50)];
self.label.backgroundColor = [UIColor lightGrayColor];
self.label.textAlignment = NSTextAlignmentLeft;
self.label.font = [UIFont systemFontOfSize:32];
[self.containView addSubview:self.label];
// ── 逐位刪除鈕 ──
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
backButton.backgroundColor = [UIColor lightGrayColor];
[backButton setFrame:CGRectMake(225, 40, 60, 50)];
[backButton setTitle:@"back" forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backClick:)
forControlEvents:UIControlEventTouchUpInside];
[self.containView addSubview:backButton];
// ── 1~9:用雙層迴圈排列 3×3 ──
NSArray *array = @[ @"1", @"2", @"3",
@"4", @"5", @"6",
@"7", @"8", @"9" ];
int n = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.button.frame = CGRectMake(30 + 65 * j, 150 + 65 * i, 60, 60);
self.button.backgroundColor = [UIColor lightGrayColor];
[self.button setTitle:array[n++] forState:UIControlStateNormal];
[self.containView addSubview:self.button];
[self.button addTarget:self action:@selector(one:)
forControlEvents:UIControlEventTouchUpInside];
}
}
// ── 0 ──
UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button0 setFrame:CGRectMake(30, 345, 60, 60)];
button0.backgroundColor = [UIColor lightGrayColor];
[button0 setTitle:@"0" forState:UIControlStateNormal];
[button0 addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
[self.containView addSubview:button0];
// ── 小數點 ──
UIButton *point = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[point setFrame:CGRectMake(95, 345, 60, 60)];
point.backgroundColor = [UIColor lightGrayColor];
[point setTitle:@"." forState:UIControlStateNormal];
[point addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
[self.containView addSubview:point];
// ── 全部清除 ──
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[deleteButton setFrame:CGRectMake(160, 345, 60, 60)];
deleteButton.backgroundColor = [UIColor lightGrayColor];
[deleteButton setTitle:@"delete" forState:UIControlStateNormal];
[deleteButton addTarget:self action:@selector(deleteClick:)
forControlEvents:UIControlEventTouchUpInside];
[self.containView addSubview:deleteButton];
// ── 四個運算子 ──
NSArray *operators = @[ @"+", @"-", @"*", @"/" ];
for (int i = 0; i < 4; i++) {
UIButton *opButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[opButton setFrame:CGRectMake(225, 150 + 65 * i, 60, 60)];
opButton.backgroundColor = [UIColor lightGrayColor];
[opButton setTitle:operators[i] forState:UIControlStateNormal];
[self.containView addSubview:opButton];
[opButton addTarget:self action:@selector(two:)
forControlEvents:UIControlEventTouchUpInside];
}
// ── 等號 ──
UIButton *istoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[istoButton setFrame:CGRectMake(30, 100, 255, 40)];
istoButton.backgroundColor = [UIColor lightGrayColor];
[istoButton setTitle:@"=" forState:UIControlStateNormal];
[istoButton addTarget:self action:@selector(isto:) forControlEvents:UIControlEventTouchUpInside];
[self.containView addSubview:istoButton];
self.string = [[NSMutableString alloc] init];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
// 數字與小數點共用同一個事件
- (void)one:(id)sender
{
// 若目前畫面顯示的是運算子,代表要開始輸入新數字,先清空
if ([self.string hasPrefix:@"+"] || [self.string hasPrefix:@"-"]
|| [self.string hasPrefix:@"*"] || [self.string hasPrefix:@"/"]) {
[self.string setString:@""];
}
// 連續輸入會自動串接,例如按 1、2、3 得到 "123"
[self.string appendString:[sender currentTitle]];
self.label.text = [NSString stringWithString:self.string];
// 轉為數值型別存起來
self.num1 = [self.label.text doubleValue];
NSLog(@"%f", self.num1);
}
- (void)two:(id)sender
{
[self.string setString:@""];
[self.string appendString:[sender currentTitle]];
self.label.text = self.string;
// 依按下的運算子記錄狀態
if ([self.string hasPrefix:@"+"]) {
self.num2 = self.num1; // 記住運算前的數字
self.num4 = 1;
} else if ([self.string hasPrefix:@"-"]) {
self.num2 = self.num1;
self.num4 = 2;
} else if ([self.string hasPrefix:@"*"]) {
self.num2 = self.num1;
self.num4 = 3;
} else if ([self.string hasPrefix:@"/"]) {
self.num2 = self.num1;
self.num4 = 4;
}
}
- (void)isto:(id)sender
{
switch (self.num4) {
case 1:
self.num3 = self.num2 + [self.label.text doubleValue];
break;
case 2:
self.num3 = self.num2 - [self.label.text doubleValue];
break;
case 3:
self.num3 = self.num2 * [self.label.text doubleValue];
break;
case 4:
self.num3 = self.num2 / [self.label.text doubleValue];
break;
default:
return; // 還沒按運算子就按等號,不做任何事
}
self.label.text = [NSString stringWithFormat:@"%f", self.num3];
[self.string setString:@""];
}
// 全部清除
- (void)deleteClick:(id)sender
{
[self.string setString:@""];
self.label.text = self.string;
self.num1 = 0;
self.num2 = 0;
self.num4 = 0;
}
// 逐位刪除(backspace)
- (void)backClick:(id)sender
{
if (self.string.length > 0) {
NSInteger n = self.string.length;
[self.string deleteCharactersInRange:NSMakeRange(n - 1, 1)];
self.label.text = self.string;
}
}
這份實作把計算機的每個環節都跑通了,但仍有幾處值得優化,也是很好的練習方向:
按下 8 ÷ 0 = 會得到 inf,畫面顯示会很奇怪。應該在 num4 為 4 時先檢查除數:
case 4:
if ([self.label.text doubleValue] == 0) {
self.label.text = @"錯誤";
return;
}
self.num3 = self.num2 / [self.label.text doubleValue];
break;
目前按兩次 . 會得到 1..2 這種非法字串。應在 one: 中加判斷:
NSString *title = [sender currentTitle];
if ([title isEqualToString:@"."] && [self.string containsString:@"."]) {
return; // 已有小數點,忽略這次輸入
}
%f 會輸出六位小數(3.000000),實用性很低。應改用:
// 去掉多餘的尾端零 NSString *result = [NSString stringWithFormat:@"%g", self.num3]; self.label.text = result;
或使用 NSNumberFormatter 做千分位與小數位控制,這也是 localization 的標準做法。
目前按 2 + 3 + 4 = 的行為不太直覺。真正的計算機應該在第二次按運算子時,先把前一步的結果算出來。
範例中所有座標都寫死(CGRectMake(30 + 65 * j, ...)),在不同尺寸螢幕上會跑版。改用 Auto Layout 或 UIStackView 會好得多——把數字鍵放進一個 3×3 的 stack,運算子放進另一個直向 stack,程式碼量還更少。
用 num1/num2/num4 這種「狀態機」實作,功能一多就會難以維護。若想支援括號與運算優先權,可以:
[[NSExpression expressionWithFormat:@"2 + 3 * 4"] evaluate]——一行就能算,但要注意它會執行任意運算式,不可用於處理使用者輸入以外的不可信字串把 UI 建立寫在 AppDelegate 是教學用的簡化寫法。正式專案應該:
viewDidLoad 中建立介面retain 與 release)UITextAlignmentLeft 已改為 NSTextAlignmentLeft做完這個練習,你對「視圖建立 → 事件綁定 → 狀態管理 → 資料轉換」這條 iOS 開發主線應該已經相當熟悉了。接著把上述七個優化逐一實作,這個小專案就能當成作品集的一部分。