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

iOS 簡易計算器實作:從視圖搭建到四則運算邏輯

編輯:iOS 開發綜合

做一個計算器是練手 iOS 的好題目:界面部分能熟悉 frame 布局、UILabel 與 UIButton 的基本用法,邏輯部分則要處理輸入緩衝、運算符優先級和狀態保存。本文記錄一個不依賴 xib、純代碼搭建的簡易版本。

整體結構

項目拆成兩個類:

  • CCLAppDelegate:負責搭建窗口、背景視圖、結果顯示標簽,以及按鈕鍵盤;
  • CCLCalculatorView:封裝一行四個按鈕,並承擔按鈕點擊後的計算邏輯。

AppDelegate:搭建界面

// CCLAppDelegate.m
// TestCalculator
//
// Created by lanouhn on 14-8-20.
// Copyright (c) 2014年 vaercly@163.com 陳聰雷. All rights reserved.

#import "CCLAppDelegate.h"
#import "CCLCalculatorView.h"

@interface CCLAppDelegate ()
{
    UIView *_backgroundView;
    UILabel *_showResultLable;
}
@end

@implementation CCLAppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [self setupbgView];
    [self setupShowView];
    [self setupCalView];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

// 背景視圖
- (void)setupbgView {
    _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
    _backgroundView.backgroundColor = [UIColor whiteColor];
    [self.window addSubview:_backgroundView];
    [_backgroundView release];
}

// 結果顯示區域
- (void)setupShowView {
    _showResultLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 280, 80)];
    _showResultLable.backgroundColor = [UIColor whiteColor];
    _showResultLable.font = [UIFont systemFontOfSize:45];
    _showResultLable.layer.cornerRadius = 6;
    _showResultLable.layer.borderColor = [UIColor grayColor].CGColor;
    _showResultLable.layer.borderWidth = 2;
    _showResultLable.textAlignment = NSTextAlignmentRight;
    [_backgroundView addSubview:_showResultLable];
    [_showResultLable release];
}

// 鍵盤區,一行四個鍵,共五行
- (void)setupCalView {
    NSArray *arr = @[@[@"MC", @"M+", @"M-", @"C"],
                     @[@7, @8, @9, @"+"],
                     @[@4, @5, @6, @"-"],
                     @[@1, @2, @3, @"*"],
                     @[@0, @".", @"/", @"="]];

    for (int i = 0; i < 5; i++) {
        CCLCalculatorView *calKeyView = [[CCLCalculatorView alloc]
                initWithFrame:CGRectMake(20, 150 + 80 * i, 280, 40)
                  buttonTitle:arr[i]];
        [_backgroundView addSubview:calKeyView];
        [calKeyView release];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

- (void)dealloc {
    [_window release];
    [super dealloc];
}

@end

CalculatorView:按鈕與計算邏輯

// CCLCalculatorView.m
// TestCalculator
//
// Created by lanouhn on 14-8-20.
// Copyright (c) 2014年 vaercly@163.com 陳聰雷. All rights reserved.

#import "CCLCalculatorView.h"

@interface CCLCalculatorView ()
{
    UIButton *_btn;
}
@end

@implementation CCLCalculatorView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 一行生成四個按鈕
        for (int i = 0; i < 4; i++) {
            _btn = [UIButton buttonWithType:UIButtonTypeSystem];
            _btn.backgroundColor = [UIColor grayColor];
            _btn.frame = CGRectMake(0 + 75 * i, 0, 55, 50);
            [_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _btn.layer.cornerRadius = 6;
            _btn.layer.masksToBounds = YES;
            _btn.titleLabel.font = [UIFont systemFontOfSize:30];
            [_btn addTarget:self action:@selector(show:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:_btn];
        }
    }
    return self;
}

// 帶標題的構造,用於給剛才那四個按鈕依次賦值
- (id)initWithFrame:(CGRect)frame buttonTitle:(NSArray *)title {
    self = [self initWithFrame:frame];
    if (self) {
        for (int i = 0; i < 4; i++) {
            UIButton *tempButton = (UIButton *)self.subviews[i];
            NSString *tempTitle = [NSString stringWithFormat:@"%@", title[i]];
            [tempButton setTitle:tempTitle forState:UIControlStateNormal];
        }
    }
    return self;
}

- (NSString *)text:(NSString *)str {
    return [NSString stringWithFormat:@"%@", _btn.titleLabel];
}

- (NSString *)show:(UIButton *)button {
    NSString *str = [NSString stringWithFormat:@"%@", button.titleLabel.text];

    // 直接從 window 的視圖層次裡取出結果標簽
    UIView *tempView = self.window.subviews[0];
    UILabel *lable = tempView.subviews[0];

    static CGFloat a;        // 保存第一個操作數
    static char b;           // 保存運算符
    static char c[10];       // 依次保存輸入的每個字符
    static int i;            // 控制保存位置

    if ([str isEqualToString:@"+"] || [str isEqualToString:@"-"]
        || [str isEqualToString:@"*"] || [str isEqualToString:@"/"]) {

        a = [lable.text floatValue];
        b = [str characterAtIndex:0];
        NSLog(@"test1 a = %g str = %@ b = %c", a, str, b);

        for (int j = 0; j < 10; j++) {
            c[j] = '\0';
        }
        i = -1;
        lable.text = nil;

    } else if ([str isEqualToString:@"="]) {

        NSLog(@"test2 a = %g str = %@ b = %c", a, str, b);
        if (b == '+') {
            lable.text = [NSString stringWithFormat:@"%g", (a + [lable.text floatValue])];
        } else if (b == '-') {
            lable.text = [NSString stringWithFormat:@"%g", (a - [lable.text floatValue])];
        } else if (b == '*') {
            lable.text = [NSString stringWithFormat:@"%g", (a * [lable.text floatValue])];
        } else {
            lable.text = [NSString stringWithFormat:@"%g", (a / [lable.text floatValue])];
        }

    } else if ([str isEqualToString:@"C"]) {    // 退格
        i--;
        c[i] = '\0';
        i--;
        lable.text = [NSString stringWithFormat:@"%s", c];

    } else if ([str isEqualToString:@"MC"]) {   // 清空
        for (int j = 0; j < 10; j++) {
            c[j] = '\0';
        }
        lable.text = [NSString stringWithFormat:@"%s", c];
        i = -1;

    } else if ([str isEqualToString:@"M+"]) {
        NSLog(@"M+");
    } else if ([str isEqualToString:@"M-"]) {
        NSLog(@"M-");
    } else {    // 數字與小數點
        c[i] = [str characterAtIndex:0];
        lable.text = [NSString stringWithFormat:@"%s", c];
    }

    i++;
    return str;
}

@end

實現思路說明

整個計算邏輯建立在三個 static 變量上:

  • a 保存第一個操作數;
  • b 保存運算符;
  • 字符數組 c 配合下標 i,逐位累積用戶當前輸入的數字。

按下運算符時,把當前顯示值轉成浮點數存進 a,記下運算符,清空緩衝區並把下標重置為 -1;按下等號時,根據 b 決定做哪種運算,結果寫回標簽。退格鍵靠下標回退並補 '\0' 截斷字符串,清空鍵則把整個數組歸零。

這份代碼的局限與改進方向

作為練習它足夠直觀,但真實項目裡這樣寫會有不少問題,值得逐條列出:

  • 視圖層次硬取:self.window.subviews[0] 再取 subviews[0] 拿標簽,完全依賴添加順序,任何一次調整都會崩。應該把結果標簽作為屬性或通過 delegate、block 回傳。
  • static 存狀態:計算狀態放在 static 變量裡,多實例會互相干擾。應改為實例屬性。
  • 不支持運算優先級:目前是「按下即算」的順序執行,2 + 3 * 4 會得到 20 而不是 14。要支持優先級,常規做法是改成逆波蘭表達式(後綴表達式)配合棧求值。
  • 除零未處理:除數為 0 時會得到 inf 或 nan,需要提前判斷。
  • 輸入長度未限制:字符數組固定 10 位,超出會越界。應加上長度校驗。
  • 浮點精度:0.1 + 0.2 這類運算會出現精度誤差,正式實現通常用 NSDecimalNumber。
  • 內存管理:代碼寫於 MRC 時代,反復 release;ARC 下這些調用都可以去掉。

把上面幾點逐一改進一遍,這個小項目就能收穫不少——尤其是「後綴表達式求值」和「用屬性替代硬取視圖」這兩項,是後續做更複雜界面時的基本功。

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