简单计算器 Basic Calculator (实例)

Basic Calculator 

 

 In this tutorial i will be showing you how to create a basic calculator 

Features: 

  •  1 Label
  • 17 Round Rect Buttons
This tutorial is a full featured app allowing you to add, minus, divide and multiply once created it can be ready to be submitted to the app store or you could expand on it and give it you own personal touch

 

The Code

calcViewController.h 


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    float result;
    int currentOperation;
    float currentNumber;
    __weak IBOutlet UILabel *calulatorScreen;
    
}

- (IBAction)buttonDigitPressed:(id)sender;
- (IBAction)buttonOperationPressed:(id)sender;
- (IBAction)cancelInput:(id)sender;
- (IBAction)cancelOperation:(id)sender;

@end
 

calcViewController.m

 

- (IBAction)buttonDigitPressed:(id)sender 
{
    currentNumber = currentNumber*10 + (float)[sender tag];
    calulatorScreen.text = [NSString stringWithFormat:@"%2f",currentNumber];
}

- (IBAction)buttonOperationPressed:(id)sender 
{
    if(currentOperation == 0) result = currentNumber;
    else
    {
        switch (currentOperation) {
            case 1:
                result = result + currentNumber;
            break;
                
            case 2:
                result = result - currentNumber;
            break;
                
            case 3:
                result = result * currentNumber;
            break;
                
            case 4:
                result = result / currentNumber;
            break;
               
            default:
                currentNumber= 0;
            break;
        }
    }
    
    currentNumber = 0;
    calulatorScreen.text = [NSString stringWithFormat:@"%2f",result];
    if([sender tag] == 0) result = 0;
    currentOperation = [sender tag];
}

- (IBAction)cancelInput:(id)sender 
{
    currentNumber = 0;
    calulatorScreen.text = @"0";
}

- (IBAction)cancelOperation:(id)sender 
{
    currentNumber = 0;
    currentOperation = 0;
    calulatorScreen.text = @"0";
}
 

 

- (void)viewDidUnload
{
    calulatorScreen = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
 

 

来源:http://www.youtube.com/watch?v=Ihw0cfNOrr4

 

 

 

 

 

你可能感兴趣的:(计算器)