您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 Objective-C 做一個功能完整的簡易計算機

編輯:iOS 開發綜合

做一個計算機是 iOS 入門的經典練習——它同時涵蓋了視圖建立、按鈕事件綁定、字串處理與基本型別轉換。以下完整實作,支援 1~9、0、小數點、四則運算、等號、全部清除與逐位刪除。

介面設計

版面規劃如下:

  • 上方:一個 UILabel 顯示輸入與結果,右側放一個 back 鈕(逐位刪除)
  • 中段:一個橫跨整行的等號鈕
  • 左側 3×3 網格:1~9
  • 下一列:0、小數點、delete(全部清除)
  • 右側直向:+ − × ÷ 四個運算子

屬性宣告

#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;
    }
}

這個版本可以更好的地方

這份實作把計算機的每個環節都跑通了,但仍有幾處值得優化,也是很好的練習方向:

1. 除零沒有處理

按下 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;

2. 小數點可以重複輸入

目前按兩次 . 會得到 1..2 這種非法字串。應在 one: 中加判斷:

NSString *title = [sender currentTitle];
if ([title isEqualToString:@"."] && [self.string containsString:@"."]) {
    return;   // 已有小數點,忽略這次輸入
}

3. 運算結果格式化

%f 會輸出六位小數(3.000000),實用性很低。應改用:

// 去掉多餘的尾端零
NSString *result = [NSString stringWithFormat:@"%g", self.num3];
self.label.text = result;

或使用 NSNumberFormatter 做千分位與小數位控制,這也是 localization 的標準做法。

4. 連續運算

目前按 2 + 3 + 4 = 的行為不太直覺。真正的計算機應該在第二次按運算子時,先把前一步的結果算出來。

5. 用格式化字串取代硬編碼 frame

範例中所有座標都寫死(CGRectMake(30 + 65 * j, ...)),在不同尺寸螢幕上會跑版。改用 Auto Layout 或 UIStackView 會好得多——把數字鍵放進一個 3×3 的 stack,運算子放進另一個直向 stack,程式碼量還更少。

6. 表達式解析的替代做法

用 num1/num2/num4 這種「狀態機」實作,功能一多就會難以維護。若想支援括號與運算優先權,可以:

  • 實作運算子優先權解析(Shunting-yard 演算法)把中序式轉為後序式再求值
  • 使用 NSExpression:[[NSExpression expressionWithFormat:@"2 + 3 * 4"] evaluate]——一行就能算,但要注意它會執行任意運算式,不可用於處理使用者輸入以外的不可信字串

7. 版面與架構

把 UI 建立寫在 AppDelegate 是教學用的簡化寫法。正式專案應該:

  • 建立一個繼承 UIViewController 的 CalculatorViewController,在 viewDidLoad 中建立介面
  • 把計算邏輯抽到獨立的 Calculator 類別,Controller 只負責畫面與事件轉發
  • 用 ARC 取代 MRC(移除所有 retain 與 release)
  • UITextAlignmentLeft 已改為 NSTextAlignmentLeft

做完這個練習,你對「視圖建立 → 事件綁定 → 狀態管理 → 資料轉換」這條 iOS 開發主線應該已經相當熟悉了。接著把上述七個優化逐一實作,這個小專案就能當成作品集的一部分。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved