adb密码计算器ios
2016-03-28 17:27:55 yuleidnf 阅读数 410

好久没写了,今天来一篇之前写的计算器的小Demo

当时还没有学UICollectionView,于是这个界面全部是有label和button写出来的

下面上代码

这是.h文件里面写的

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    UILabel *_label;//显示框
    int     a;//数字的tag
    int     b;//运算符的tag
    float     result;//结果
    BOOL    flag;//判断是非按等号
}


@end

这是.m文件里面写的

  1 #import "ViewController.h"
  2 #define HEIGHT     [[UIScreen mainScreen] bounds].size.height
  3 #define WIDTH      [[UIScreen mainScreen] bounds].size.width
  4 @interface ViewController ()
  5 
  6 @end
  7 
  8 @implementation ViewController
  9 
 10 - (void)viewDidLoad {
 11     [super viewDidLoad];
 12     [self creat];
 13     // Do any additional setup after loading the view, typically from a nib.
 14 }
 15 - (void)creat{
 16     UIImage *num001 = [UIImage imageNamed:@"001.png"];
 17     UIImage *num002 = [UIImage imageNamed:@"002.png"];
 18     UIImage *num101 = [UIImage imageNamed:@"101.png"];
 19     UIImage *num102 = [UIImage imageNamed:@"102.png"];
 20     UIImage *num201 = [UIImage imageNamed:@"201.png"];
 21     UIImage *num202 = [UIImage imageNamed:@"202.png"];
 22     UIImage *num301 = [UIImage imageNamed:@"301.png"];
 23     UIImage *num302 = [UIImage imageNamed:@"302.png"];
 24     UIImage *num401 = [UIImage imageNamed:@"401.png"];
 25     UIImage *num402 = [UIImage imageNamed:@"402.png"];
 26     UIImage *num501 = [UIImage imageNamed:@"501.png"];
 27     UIImage *num502 = [UIImage imageNamed:@"502.png"];
 28     UIImage *num601 = [UIImage imageNamed:@"601.png"];
 29     UIImage *num602 = [UIImage imageNamed:@"602.png"];
 30     UIImage *num701 = [UIImage imageNamed:@"701.png"];
 31     UIImage *num702 = [UIImage imageNamed:@"702.png"];
 32     UIImage *num801 = [UIImage imageNamed:@"801.png"];
 33     UIImage *num802 = [UIImage imageNamed:@"801.png"];
 34     UIImage *num901 = [UIImage imageNamed:@"901.png"];
 35     UIImage *num902 = [UIImage imageNamed:@"902.png"];
 36     
 37     
 38     UIImage *calj01 = [UIImage imageNamed:@"j01.png"];
 39     UIImage *calj02 = [UIImage imageNamed:@"j02.png"];
 40     UIImage *caljj01 = [UIImage imageNamed:@"jj01.png"];
 41     UIImage *caljj02 = [UIImage imageNamed:@"jj02.png"];
 42     UIImage *calc01 = [UIImage imageNamed:@"c01.png"];
 43     UIImage *calc02 = [UIImage imageNamed:@"c02.png"];
 44     UIImage *calcc01 = [UIImage imageNamed:@"cc01.png"];
 45     UIImage *calcc02 = [UIImage imageNamed:@"cc02.png"];
 46     UIImage *cald01 = [UIImage imageNamed:@"d01.png"];
 47     UIImage *cald02 = [UIImage imageNamed:@"d02.png"];
 48     UIImage *caldd = [UIImage imageNamed:@"dd01.png"];
 49     
 50     
 51     
 52     
 53     self.view.backgroundColor = [UIColor whiteColor];
 54     _label = [[UILabel alloc]initWithFrame:CGRectMake(20, 40, WIDTH - 40, 80)];
 55     _label.backgroundColor = [UIColor blackColor];
 56     _label.textColor = [UIColor whiteColor];
 57     _label.textAlignment = NSTextAlignmentRight;
 58     _label.font = [UIFont systemFontOfSize:30];
 59     _label.lineBreakMode = NSLineBreakByTruncatingHead;
 60     _label.text = @"0";
 61     [self.view addSubview:_label];
 62     
 63     UIButton *clearBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 130, (WIDTH-55)/4, (WIDTH-55)/4)];
 64     [clearBtn setTitle:@"C" forState:UIControlStateNormal];
 65 
 66     [clearBtn setImage:[UIImage imageNamed:@"ccc01.png"] forState:UIControlStateNormal];
 67     clearBtn.tag = 1;
 68     [clearBtn addTarget:self action:@selector(deleteInfo:) forControlEvents:UIControlEventTouchUpInside];
 69     [self.view addSubview:clearBtn];
 70     
 71     UIButton *deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-100, 130, (WIDTH-55)/4, (WIDTH-55)/4)];
 72     deleteBtn.tag = 2;
 73     [deleteBtn setTitle:@"<-" forState:UIControlStateNormal];
 74 
 75     [deleteBtn setImage:[UIImage imageNamed:@"t02.png"] forState:UIControlStateNormal];
 76     [deleteBtn setImage:[UIImage imageNamed:@"t01.png"] forState:UIControlStateHighlighted];
 77     [deleteBtn addTarget:self action:@selector(deleteInfo:) forControlEvents:UIControlEventTouchUpInside];
 78     [self.view addSubview:deleteBtn];
 79     NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"+",@"4",@"5",@"6",@"-",@"7",@"8",@"9",@"x",@".",@"0",@"=",@"/", nil];
 80     NSArray *back01 = @[num101,num201,num301,calj02,num401,num501,num601,caljj02,num701,num801,num901,calc02,caldd,num001,cald02,calcc02];
 81     NSArray *back02 = @[num102,num202,num302,calj01,num402,num502,num602,caljj01,num702,num802,num902,calc01,caldd,num002,cald01,calcc01];
 82     for (int i = 0; i< arr.count; i++) {
 83         UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20+i%4*((WIDTH-55)/4 + 5), 220+i/4 * ((WIDTH-55)/4 +5), (WIDTH-55)/4, (WIDTH-55)/4)];
 84         btn.tag = i+1;
 85         [btn setImage:[back01 objectAtIndex:i] forState:UIControlStateNormal];
 86         [btn setImage:[back02 objectAtIndex:i] forState:UIControlStateHighlighted];
 87         [btn setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
 88         [btn addTarget:self action:@selector(manage:) forControlEvents:UIControlEventTouchUpInside];
 89         [self.view addSubview:btn];
 90         
 91     }
 92     flag = NO;
 93     a = 0;
 94 }
 95 -(void)deleteInfo:(UIButton *)btn{
 96     if (btn.tag == 1) {
 97         _label.text = @"0";
 98         a = 0;
 99     }else{
100         if (_label.text.length == 1) {
101             _label.text = @"0";
102             return;
103         }
104         _label.text = [_label.text substringToIndex:_label.text.length-1];
105     }
106 }
107 -(void)manage:(UIButton *)btn{
108     if (btn.tag%4 == 0||btn.tag == 15) {
109         flag = YES;
110         b = a;
111         a = (int)btn.tag;
112         //  NSLog(@"%f",b);
113         if (b == 0) {
114             result = [_label.text floatValue];
115         }else{
116             switch (b/4) {
117                 case 1:
118                     result  += [_label.text floatValue];
119                     break;
120                 case 2:
121                     result  -= [_label.text floatValue];
122                     break;
123                 case 3:
124                     result  *= [_label.text floatValue];
125                     break;
126                 case 4:
127                     result  /= [_label.text floatValue];
128                     break;                default:
129                     
130                     break;
131             }
132             
133         }
134         if (result > (int)result) {
135             _label.text = [NSString stringWithFormat:@"%.2f",result];
136         }else{
137             _label.text = [NSString stringWithFormat:@"%d",(int)result];
138         }
139         if (btn.tag == 15) {
140             result = 0;
141             a = 0;
142         }
143         
144     }else if(btn.tag != 13){
145         if ([_label.text isEqualToString:@"0"]) {
146             _label.text = @"";
147         }
148         if (flag == YES) {
149             flag = NO;
150             _label.text = @"";
151         }
152         if (btn.tag == 14) {
153             _label.text = [_label.text stringByAppendingString:@"0"];
154         }else{
155             _label.text = [_label.text stringByAppendingFormat:@"%zi",btn.tag - btn.tag/4];
156         }
157     }else{
158         NSRange range = [_label.text rangeOfString:@"."];
159         if (range.location == NSNotFound) {
160             _label.text = [_label.text stringByAppendingString:@"."];
161         }
162     }
163 }
164 - (void)didReceiveMemoryWarning {
165     [super didReceiveMemoryWarning];
166     // Dispose of any resources that can be recreated.
167 }
168 
169 @end

这就是全部的内容了,希望能够帮到有用的同学们

这个没有实现里四则运算,只能在按第二个运算符的时候计算出上一个运算符元算出来的结果在进行下一步计算

如果有错误的地方,希望大家指出,小弟感激不尽

下面给一个Demo的下载地址:https://github.com/sosoneo/Calculator

2015-12-22 15:35:57 super_man_ww 阅读数 593

@interface ViewController ()

@property (nonatomic, strong) UILabel  *label;
@property (nonatomic, strong) NSString *operator1;
@property (nonatomic, strong) NSString *operator2;
@property (nonatomic, strong) NSString *operand;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createCalculator];
}

- (void)createCalculator
{
    self.operand = self.operator1 = self.operator2 = @"";
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, self.view.bounds.size.width-20, 60)];
    self.label.backgroundColor    = [UIColor grayColor];
    self.label.layer.cornerRadius = 5;
    self.label.numberOfLines      = 2;
    self.label.textAlignment      = NSTextAlignmentRight;
    [self.view addSubview:self.label];
    
    // 第一行按钮
    CGRect frame     = CGRectZero;
    NSArray *titles0 = @[@"MC", @"M+", @"M-", @"MR", @"清除"];
    CGFloat padding  = 10;
    CGFloat buttonWidth  = (self.view.bounds.size.width-(titles0.count+1)*padding)/titles0.count;
    CGFloat buttonHeight = 50;
    for (int i = 0; i < titles0.count; i++) {
        frame = CGRectMake(padding+i*(padding+buttonWidth), CGRectGetMaxY(self.label.frame)+padding, buttonWidth, buttonHeight);
        [self addButtonWithRect:frame title:titles0[i]];
    }
    
    // 其他按钮
    NSArray *titles1 = @[@"7", @"8", @"9", @"+",
                         @"4", @"5", @"6", @"-",
                         @"1", @"2", @"3", @"*",
                         @"0", @".", @"=", @"/"];
    buttonWidth = (self.view.bounds.size.width-5*padding)/4;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            [self addButtonWithRect:CGRectMake(padding+j*(padding+buttonWidth), CGRectGetMaxY(frame) + padding + i*(padding+buttonHeight), buttonWidth, buttonHeight) title:titles1[i*4+j]];
        }
    }
}

- (void)addButtonWithRect:(CGRect)rect title:(NSString *)title
{
    UIButton *button          = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame              = rect;
    button.backgroundColor    = [UIColor grayColor];
    button.layer.cornerRadius = 10;
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonClick:(UIButton *)button
{
    // 以M开头的按钮不处理
    if ([button.titleLabel.text hasPrefix:@"M"]) {
        return;
    }
    
    // 清除按钮被点击
    if ([button.titleLabel.text isEqualToString:@"清除"]) {
        self.operand    = @"";
        self.operator1  = @"";
        self.operator2  = @"";
        self.label.text = @"";
        return;
    }
    
    NSString *strInput = button.titleLabel.text;
    
    if ([self isOperand:strInput]) {  // 如果是运算符
        if (self.operand.length) { // 如果当前已经有一个操作符了,则对当前的两个操作数进行运算
            float result;
            float operator1 = [_operator1 floatValue];
            float operator2 = [_operator2 floatValue];
            if ([self.operand isEqualToString:@"+"]) {
                result = operator1 + operator2;
            } else if ([_operand isEqualToString:@"-"]) {
                result = operator1 - operator2;
            } else if ([_operand isEqualToString:@"*"]) {
                result = operator1 * operator2;
            } else if ([_operand isEqualToString:@"/"]) {
                result = operator1 / operator2;
            }
            
            self.operator1 = [NSString stringWithFormat:@"%0.2f", result];
            self.operator2 = @"";
            
            if ([strInput isEqualToString:@"="]) {
                self.operand = @"";
            } else {
                self.operand = strInput;
            }

            self.label.text = self.operator1;
        } else {
            self.operand = strInput;
        }
    } else { // 不是运算符,是操作数
        if (self.operand.length) { // 当前有操作符,这是第二操作数
            self.operator2 = [self.operator2 stringByAppendingString:strInput];
        } else {
            self.operator1 = [self.operator1 stringByAppendingString:strInput];
        }
    }
    
    if (_operator2.length) {
        _label.text = [NSString stringWithFormat:@"%@\n%@", _operator2, _operand];
    } else {
        _label.text = [NSString stringWithFormat:@"%@\n%@", _operator1, _operand];
    }
}

// 判断参数str是否为运算符
// 返回值为TRUE代表是运算符,FALSE代表不是运算符
- (BOOL)isOperand:(NSString *)str
{
    NSRange range = [str rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"+-*/="]];
    if (range.location != NSNotFound) {
        return YES;
    }
    return NO;
}

@end
2014-07-31 20:00:39 zyb050607 阅读数 750

         可以连续运算,有小数点、百分号。

AppDelegate.h

 



#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

{
    UILabel*_label;
}
@property (strong, nonatomic) UIWindow *window;
//存储操作符
@property(assign,nonatomic)int oper;
//存储第一个操作数
@property(assign,nonatomic)float one;
//判断小数点
@property(assign,nonatomic)BOOL point;
//判断连续运算
@property(assign,nonatomic)BOOL con;
//是否刚按过等于号
@property(assign,nonatomic)BOOL equal;
@end

 

//
//  AppDelegate.m
//

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    UIView *view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [self.window makeKeyAndVisible];
    [self.window addSubview:view];
    
    //结果输出label
    _label=[[UILabel alloc]initWithFrame:CGRectMake(20, 30, 280, 55)];
    _label.textColor=[UIColor whiteColor];
    _label.textAlignment=NSTextAlignmentRight;
    _label.backgroundColor=[UIColor blackColor];
    _label.font=[UIFont systemFontOfSize:30];
    _label.text=@"0";
    [view addSubview:_label];
    [_label release];
    
    //循环产生除了最后一行的button
    int x=20;
    int y=95;
    for (int i=0; i<16; i++) {
        UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
        
        button.frame=CGRectMake(x, y, 55, 55);
        NSString*picName=[NSString stringWithFormat:@"%d",i];
        [button setImage:[UIImage imageNamed:picName] forState:UIControlStateNormal];
        button.tag=i+1001;
//      button.backgroundColor=[UIColor cyanColor];
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        x=x+75;
        if ((i+1)%4==0) {
            y=y+75;
        }
        if(x>=320)x=20;
    }
    //最后一行
    //0按键
    UIButton*button0=[UIButton buttonWithType:UIButtonTypeCustom];
    button0.frame=CGRectMake(20, 395, 130, 55);
    [button0 setImage:[UIImage imageNamed:@"0_btn_highlighted"] forState:UIControlStateNormal];
    [button0 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    button0.tag=1017;
    [view addSubview:button0];
    //点按键
    UIButton*buttonPoint=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonPoint.frame=CGRectMake(170, 395, 55, 55);
    [buttonPoint setImage:[UIImage imageNamed:@"dian_btn_highlighted"] forState:UIControlStateNormal];
    buttonPoint.tag=1018;
    [buttonPoint addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:buttonPoint];
    
    //等号
    UIButton*buttonDeng=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonDeng.frame=CGRectMake(245, 395, 55, 55);
    [buttonDeng setImage:[UIImage imageNamed:@"dengyu_btn_highlighted"] forState:UIControlStateNormal];
    buttonDeng.tag=1019;
    [buttonDeng addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:buttonDeng];
    return YES;
}
//功能实现
-(void)click:(UIButton*)button{
    int tag=button.tag;
    NSMutableString*temp=[[NSMutableString alloc]init] ;
    //非数字键
    if (tag==1001||tag==1002||tag==1003||tag==1004||tag==1008||tag==1012||tag==1016) {
        switch (tag) {
            case 1004:{
                //判断是不是连续运算
                if (_oper!=0) {
                    _con=YES;
                    switch (self.oper) {
                        case 1:
                            _one=_one+[_label.text floatValue];
                            break;
                        case 2:
                            _one=_one-[_label.text floatValue];
                            break;
                        case 3:
                            _one=_one*[_label.text floatValue];
                            break;
                        case 4:
                            _one=_one/[_label.text floatValue];                            break;
                    }
                    temp=[NSMutableString stringWithFormat:@"%g",_one];
                }
                //存储本次操作符
                _oper=4;
                break;
            }
        //乘号
            case 1008:
                if (_oper!=0) {
                    _con=YES;
                    switch (self.oper) {
                        case 1:
                            _one=_one+[_label.text floatValue];
                            break;
                        case 2:
                            _one=_one-[_label.text floatValue];
                            break;
                        case 3:
                            _one=_one*[_label.text floatValue];
                            break;
                        case 4:
                            _one=_one/[_label.text floatValue];                            break;
                    }
                    
                    
                    temp=[NSMutableString stringWithFormat:@"%g",_one];
                }
                _oper=3;
                break;
                //加号
            case 1012:{
                if (_oper!=0) {
                   _con=YES;
                    switch (self.oper) {
                        case 1:
                            _one=_one+[_label.text floatValue];
                            break;
                        case 2:
                           _one=_one-[_label.text floatValue];
                            break;
                        case 3:
                            _one=_one*[_label.text floatValue];
                            break;
                        case 4:
                           _one=_one/[_label.text floatValue];                            break;
                    }
                temp=[NSMutableString stringWithFormat:@"%g",_one];
                }
                _oper=1;
                break;
            }
                //减号
            case 1016:
                if (_oper!=0) {
                    _con=YES;
                    switch (self.oper) {
                        case 1:
                            _one=_one+[_label.text floatValue];
                            break;
                        case 2:
                            _one=_one-[_label.text floatValue];
                            break;
                        case 3:
                            _one=_one*[_label.text floatValue];
                            break;
                        case 4:
                            _one=_one/[_label.text floatValue];                            break;
                    }
                    
                    
                    temp=[NSMutableString stringWithFormat:@"%g",_one];
                }
                _oper=2;
                break;
                //清除按键
            case 1001:
                _oper=0;
                temp=[NSMutableString stringWithString:@"0"];
                break;
                
               case 1002:
                temp=[NSMutableString stringWithFormat:@"%g",-[_label.text floatValue]];
                break;
            case 1003:
                temp=[NSMutableString stringWithFormat:@"%g",[_label.text floatValue]/100];
                break;
            default:
                break;
        }
           _point=NO;
        _one=[_label.text floatValue];
        [_label setText:temp];
    }
    //等号
    else if (tag==1019) {
        float two=[_label.text floatValue];
        float result = 0;
        switch (self.oper) {
            case 1:
                result=self.one+two;
                break;
            case 2:
                result=self.one-two;
                break;
            case 3:
                result=self.one*two;
                break;
            case 4:
                result=self.one/two;
                break;
        }
        _equal=YES;
        _point=NO;
        _oper=0;
        temp=[NSMutableString stringWithFormat:@"%g",result];
        [_label setText:temp];

    }//=
    
    //按下小数点
    else if (tag==1018) {
        if (_point) {
        }
        else {
            if ([_label.text floatValue]==0) {
                [temp appendString:@"0."];
                  _point=YES;
            }
            else{
                
            [temp setString:_label.text];
            [temp appendString:@"."];
            _point=YES;
            }
            [_label setText:temp];
        }
        
    }
    
    //数字键
    else{
        int number;
        switch (tag) {
            case 1005://7
                number=7;
                break;
            case 1006://8
                number=8;
                break;
            case 1007://9
                number=9;
                break;
            case 1009://4
                number=4;
                break;
            case 1010://5
                number=5;
                break;
            case 1011://6
                number=6;
                break;
            case 1013://1
                number=1;
                break;
            case 1014://2
                number=2;
                break;
            case 1015://3
                number=3;
                break;
            case 1017://0
                number=0;
                break;
                
            default:
                break;
        }
        
        if (_label.text!=nil&&number!=0) {
            [temp setString:_label.text];

        }
        if ([_label.text floatValue]!=0&&number==0) {
           [temp setString:_label.text];
        }
        if ([_label.text floatValue]==0&&number!=0&&[_label.text length]==1) {
            temp=[NSMutableString stringWithString:@""];
        }
        if (_con) {
            _one=[_label.text floatValue];
            temp=[NSMutableString stringWithString:@""];
            _con=NO;
        }
        if (_equal) {
            temp=[NSMutableString stringWithString:@""];
            _equal=NO;
        }
        [temp appendString:[NSString stringWithFormat:@"%d",number]];
            [_label setText:temp];
    }
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


效果图:

 

 

 

 

 

 

 

2016-01-03 14:07:00 weixin_33946020 阅读数 2

//

//  ViewController.m

//  计算器

 

//屏幕的宽和高

#define SCREEN_W self.view.frame.size.width

#define SCREEN_H self.view.frame.size.height

 

 

#import "ViewController.h"

 

@interface ViewController ()

//用于存储输入的第一个数字

@property (nonatomic,assign) CGFloat num1;

//用于存储输入的第二个数字

@property (nonatomic,assign) CGFloat num2;

//用于存储最终结果

@property (nonatomic,assignCGFloat numResult;

//用于判断符号的标记

@property (nonatomic,assign) NSInteger tag;

//显示屏

@property (nonatomic,strong) UILabel *screen;

//

@property (nonatomic,strong) NSMutableString *str;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    //开辟空间

    _str = [[NSMutableString alloc]init];

    // Do any additional setup after loading the view, typically from a nib.

#pragma mark - screen

    //先创建一个标签,用于显示

    _screen = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-400-5*10)];

    //设置屏幕的字体颜色

    [_screen setTextColor:[UIColor whiteColor]];

    //设置屏幕的背景颜色

    _screen.backgroundColor = [UIColor blackColor];

    //设置屏幕的字体大小

    _screen.font = [UIFont systemFontOfSize:40];

    //设置屏幕的字体自适应

    _screen.adjustsFontSizeToFitWidth = YES;

    //设置字体的对齐方式

    _screen.textAlignment = NSTextAlignmentRight;

    //清零

    _screen.text = [NSMutableString stringWithString:@"0"];

    [self.view addSubview:_screen];

    

#pragma mark - buttonwith+_*/

    NSArray *signArr = @[@"÷",@"x",@"-",@"+"];

    for (int i = 0; i < [signArr count]; i++) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];

        //设置按钮的文字

        [btn setTitle:signArr[i] forState:UIControlStateNormal];

        //设置按钮的位置和大小

        btn.frame = CGRectMake(((SCREEN_W-30)/4.0)*3.0+30, _screen.frame.size.height+90*(i%4)+10, (SCREEN_W-30)/4.0, 80);

        //设置按钮的背景颜色

        btn.backgroundColor = [UIColor orangeColor];

        //设置按钮字体的大小

        btn.titleLabel.font = [UIFont systemFontOfSize:40];

        //给每个按钮添加事件

        [btn addTarget:self action:@selector(calculate:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:btn];

    }

    

#pragma mark - 单独添加

    UIButton *goBtn = [UIButton buttonWithType:UIButtonTypeSystem];

    //设置按钮的大小和位置

    goBtn.frame = CGRectMake(((SCREEN_W-30)/4.0)*3.0+30, _screen.frame.size.height+90*4+10, (SCREEN_W-30)/4.0, 80);

    //设置按钮的背景颜色

    goBtn.backgroundColor = [UIColor orangeColor];

    //设置按钮的文字

    [goBtn setTitle:@"=" forState:UIControlStateNormal];

    //设置文字的大小

    goBtn.titleLabel.font = [UIFont systemFontOfSize:40];

    //为每个按钮添加事件

    [goBtn addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:goBtn];

 

#pragma mark - number

    NSArray *numArr = @[@"7",@"8",@"9",@"4",@"5",@"6",@"1",@"2",@"3"];

    for (int i = 0 ; i < [numArr count]; i++) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

        //设置按钮的大小和位置

        btn.frame = CGRectMake(((SCREEN_W-30)/4.0+10)*(i%3), _screen.frame.size.height+90*(i/3)+90+10, (SCREEN_W-30)/4.0, 80);

        //设置按钮的背景颜色

        btn.backgroundColor = [UIColor lightGrayColor];

        //设置按钮的文字

        [btn setTitle:numArr[i] forState:UIControlStateNormal];

        //设置文字的大小

        btn.titleLabel.font = [UIFont systemFontOfSize:40];

        //设置文字的颜色

        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        //为每个按钮添加事件

        [btn addTarget:self action:@selector(expressNum:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:btn];

    }

#pragma mark - 添加清除键

    UIButton *cleanBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    cleanBtn.frame = CGRectMake(0, _screen.frame.size.height+10, (SCREEN_W-30)/4.0, 80);

    //设置按钮的背景颜色

    cleanBtn.backgroundColor = [UIColor lightGrayColor];

    //设置按钮的文字

    [cleanBtn setTitle:@"AC" forState:UIControlStateNormal];

    //设置文字的大小

    cleanBtn.titleLabel.font = [UIFont systemFontOfSize:40];

    //设置文字的颜色

    [cleanBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    //为每个按钮添加事件

    [cleanBtn addTarget:self action:@selector(clean:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:cleanBtn];

 

    

#pragma mark - 单独添加0

    UIButton *btn0 = [UIButton buttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    btn0.frame = CGRectMake(0, SCREEN_H - 80, (SCREEN_W-30)/4.0*2+10, 80);

    //设置按钮的背景颜色

    btn0.backgroundColor = [UIColor lightGrayColor];

    //设置按钮的文字

    [btn0 setTitle:@"0" forState:UIControlStateNormal];

    //设置文字的大小

    btn0.titleLabel.font = [UIFont systemFontOfSize:40];

    //设置文字的颜色

    [btn0 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    //为每个按钮添加事件

    [btn0 addTarget:self action:@selector(expressNum:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn0];

 

#pragma mark - 单独添加百分号%

    UIButton *btnPrecent = [UIButton buttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    btnPrecent.frame = CGRectMake(((SCREEN_W-30)/4.0+10)*2, _screen.frame.size.height+10, (SCREEN_W-30)/4.0, 80);

    //设置按钮的背景颜色

    btnPrecent.backgroundColor = [UIColor lightGrayColor];

    //设置按钮的文字

    [btnPrecent setTitle:@"%" forState:UIControlStateNormal];

    //设置文字的大小

    btnPrecent.titleLabel.font = [UIFont systemFontOfSize:40];

    //设置文字的颜色

    [btnPrecent setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    //为每个按钮添加事件

    [btnPrecent addTarget:self action:@selector(precent:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnPrecent];

 

 

#pragma mark - 单独添加点"."

    UIButton *btnPoint = [UIButton buttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    btnPoint.frame = CGRectMake(btn0.frame.size.width+10, SCREEN_H-80, (SCREEN_W-30)/4.0, 80);

    //设置按钮的背景颜色

    btnPoint.backgroundColor = [UIColor lightGrayColor];

    //设置按钮的文字

    [btnPoint setTitle:@"." forState:UIControlStateNormal];

    //设置文字的大小

    btnPoint.titleLabel.font = [UIFont systemFontOfSize:40];

    //设置文字的颜色

    [btnPoint setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    //为每个按钮添加事件

    [btnPoint addTarget:self action:@selector(expressNum:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnPoint];

    

#pragma mark - 单独添加点"+/-"

    UIButton *btnSign = [UIButton buttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    btnSign.frame = CGRectMake(cleanBtn.frame.size.width+10, _screen.frame.size.height+10, (SCREEN_W-30)/4.0, 80);

    //设置按钮的背景颜色

    btnSign.backgroundColor = [UIColor lightGrayColor];

    //设置按钮的文字

    [btnSign setTitle:@"+/-" forState:UIControlStateNormal];

    //设置文字的大小

    btnSign.titleLabel.font = [UIFont systemFontOfSize:40];

    //设置文字的颜色

    [btnSign setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    //为每个按钮添加事件

    [btnSign addTarget:self action:@selector(signNum:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnSign];

 

}

 

 

-(void) expressNum:(UIButton *)sender

{

    

    //先判断首字母是不是符号

    if ([_str hasPrefix:@"+"]||[_str hasPrefix:@"-"]||[_str hasPrefix:@"x"]||[_str hasPrefix:@"÷"]) {

        //如果是,就清零

        _str = [NSMutableString stringWithString:@""];

    }

    //连续追加数字

    [_str appendString:sender.currentTitle];

    _screen.text = [NSString stringWithString:_str];

    //将输入的第一个数字保存在num1

    _num1 = [_screen.text doubleValue];

    //用于调试

    //NSLog(@"-----%ld",_num1);

}

//判断符号

-(void)calculate:(UIButton *)sender

{

    //先清零

    _str = [NSMutableString stringWithString:@""];

    //再重新追加符号

    [_str appendString:sender.currentTitle];

    //显示(这个可写可不写)

    _screen.text = [NSString stringWithString:_str];

    if ([_str hasPrefix:@"+"]) {

        _num2 = _num1;

        _tag = 1;

    }else if ([_str hasPrefix:@"-"]){

        _num2 = _num1;

        _tag = 2;

    }else if ([_str hasPrefix:@"x"]) {

        _num2 = _num1;

        _tag = 3;

    }else if ([_str hasPrefix:@"÷"]) {

        _num2 = _num1;

        _tag = 4;

    }

    

}

//计算结果

-(void)go:(UIButton *)sender

{

    switch (_tag) {

        case 1:

            _numResult = _num2 + _num1;

            break;

        case 2:

            _numResult = _num2 - _num1;

            break;

        case 3:

            _numResult = _num2 * _num1;

            break;

        case 4:

            _numResult = _num2 / _num1;

            break;

    }

    _screen.text = [NSString stringWithFormat:@"%lg",_numResult];

    _num1 = _numResult;

}

//清除

-(void)clean:(UIButton *)sender

{

    _str = [NSMutableString stringWithString:@""];

    _screen.text = @"0";

    _num1 = 0;

    _num2 = 0;

    _numResult = 0;

}

 

//百分号

-(void)precent:(UIButton *)sender

{

    _num1 = _num1 * 0.01;

    //注意,这里要以最简形式(占用宽度最小)输出,并且不会输出无意义的0

    _screen.text = [NSString stringWithFormat:@"%lg",_num1];

}

//正负号

-(void)signNum:(UIButton *)sender

{

    //先判断数字是否大于0,如果是,就变负

    if (_num1 >= 0) {

        //添加负号

        [_str insertString:@"-" atIndex:0];

        _num1 = [_str doubleValue];

        _screen.text = [NSString stringWithFormat:@"%lg",_num1];

    }

    //如果数字小于0,那么变为正数

    else if (_num1 < 0)

    {

        //删除负号

        [_str deleteCharactersInRange:NSMakeRange(0, 1)];

        _num1 = [_str doubleValue];

        _screen.text = [NSString stringWithFormat:@"%lg",_num1];

    }

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

 

 

 

 

//大家看了之后觉得哪里代码可以更加优化,或者功能上有什么补充的,麻烦评论下,感谢了🙏


 

转载于:https://www.cnblogs.com/Mr-Lin/p/5096308.html

2013-12-04 11:47:49 u012891525 阅读数 874

步骤:

1.打开Xcode,单机Creat new Xcode project

2.左边选择ios下Application,右边选择single view Application

3.填写项目名称单机Next

4.ViewController.h中定义成员和方法

#import

@interface ViewController : UIViewController
@property(retain,nonatomic)UIButton *button;
@property(retain,nonatomic)UILabel *label;
@property(retain,nonatomic)NSMutableString *string;
@property(assign,nonatomic)double num1,num2,num3,num4;
@end

4.ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize button,label,string,num1,num2,num3,num4;//string保存字符,显示数值。num1是存输入的数值,num2是存运算符前的数值,num3是运算结果,num4是判断进行何种运算
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    //设置背景图片
    NSBundle *bundle=[NSBundle mainBundle];
    NSData *data=[[NSData alloc]initWithContentsOfFile:
                  [bundle pathForResource:@"1" ofType:@"jpg"]];//找到NSBundle的某一资源
    UIImage *img=[UIImage imageWithData:data];//创建了可用的图像对象
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:img]];//UIColor colorWithPatternImage:方法是把图片转化为color类型  将背景换做提供的图片
   
    //添加提示性文字
    UIAlertView *alex=[[UIAlertView alloc]initWithTitle:@"使用说明" message:@"只支持两数的计算以及在此基础上的计算,不支持连算。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alex show];
    [alex release];

    //创建标签
    self.label=[[UILabel alloc]initWithFrame:CGRectMake(90, 40, 200, 50)];
    [self.view addSubview:label];
    self.label.backgroundColor=[UIColor clearColor];//清空背景颜色
    self.label.textColor=[UIColor blueColor];//字体颜色
    self.label.textAlignment=UITextAlignmentRight;//字体居右
    self.label.font=[UIFont systemFontOfSize:32.4];
   
    //添加1-9数字
    NSArray *array=[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];
    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 setTitle:[array objectAtIndex:n++] forState:UIControlStateNormal];
            [self.view addSubview:button];
            [self.button addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    //单独添加0
    UIButton *button0=[UIButton buttonWithType:UIButtonTypeRoundedRect];
   
    [button0 setFrame:CGRectMake(30, 345, 60, 60)];
   
    [button0 setTitle:@"0" forState:UIControlStateNormal];
   
    [button0 addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button0];
   
       
    //添加运算符
    NSArray *array1=[NSArray arrayWithObjects:@"+",@"-",@"*",@"/",nil];
    for (int i=0; i<4; i++)
    {
        UIButton *button1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button1 setFrame:CGRectMake(225, 150+65*i, 60, 60)];
        [button1 setTitle:[array1 objectAtIndex:i] forState:UIControlStateNormal];
        [self.view addSubview:button1];
        [button1 addTarget:self action:@selector(two:) forControlEvents:UIControlEventTouchUpInside];
    }
   
    //添加=
   
    UIButton *button2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
   
    [button2 setFrame:CGRectMake(160, 410, 125, 35)];
   
    [button2 setTitle:@"=" forState:UIControlStateNormal];
   
    [button2 addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
   
    //添加清除键
   
    UIButton *button3=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button3 setFrame:CGRectMake(30, 410, 125, 35)];
    [button3 setTitle:@"AC" forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(clean:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];
   
    //添加.
   
    UIButton *button4=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button4 setFrame:CGRectMake(95, 345, 60, 60)];
    [button4 setTitle:@"." forState:UIControlStateNormal];
    [button4 addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button4];
   
    //后退
   
    UIButton *button5=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button5 setFrame:CGRectMake(160, 345, 60, 60)];
    [button5 setTitle:@"back" forState:UIControlStateNormal];
    [button5 addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
   
    [self.view addSubview:button5];
   
   
    self.string=[[NSMutableString alloc]init];//初始化可变字符串,分配内存
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)one:(id)sender
{
    //保证是符号时在输入数字时隐藏
    if ([self.string hasPrefix:@"+"]||[self.string hasPrefix:@"-"]||[self.string hasPrefix:@"*"]||[self.string hasPrefix:@"/"])//判断是否为运算符
    {
        [self.string setString:@""];//字符串清零
    }
    [self.string appendString:[sender currentTitle]];//数字连续输入
    self.label.text=[NSString stringWithString: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=[NSString stringWithString:string];
   
    //判断输入是+号
    if ([self.string hasPrefix:@"+"])//hasPrefix:判断字符串以加号开头
    {
        self.num2=self.num1;//将前面的数值保存在num2里
        self.num4=1;
    }
    //判断输入是-号
    else if([self.string hasPrefix:@"-"])//hasPrefix:判断字符串以减号开头
    {
        self.num2=self.num1;
        self.num4=2;
    }
    //判断输入是*号
    else if([self.string hasPrefix:@"*"])//hasPrefix:判断字符串以乘号开头
    {
        self.num2=self.num1;
        self.num4=3;
    }
    //判断输入是/号
    else if([self.string hasPrefix:@"/"])//hasPrefix:判断字符串以除号开头
    {
        self.num2=self.num1;
        self.num4=4;
    }
}


-(void)go:(id)sender
{
        //判断输入是+号
    if (self.num4==1)
    {
        self.num3=self.num2+[self.label.text doubleValue];//[self.label.text doubleValue]是每次后输入的数字
        self.label.text=[NSString stringWithFormat:@"%f",self.num3];//显示结果
        self.num1=[self.label.text doubleValue];//为了可以连加。保存结果
        self.num3=0;
        [self.string setString:@""];//保证每次结果正确输出后,再次计算,不用按清除键
    }
    //判断输入是-号
    else if(self.num4==2)
    {
        self.num3=self.num2-[self.label.text doubleValue];
        self.label.text=[NSString stringWithFormat:@"%f",self.num3];
        self.num1=[self.label.text doubleValue];
        self.num3=0;
        [self.string setString:@""];
    }
    //判断输入是*号
    else if(self.num4==3)
    {
        self.num3=self.num2*[self.label.text doubleValue];
        self.label.text=[NSString stringWithFormat:@"%f",self.num3];
        self.num1=[self.label.text doubleValue];
        self.num3=0;
        [self.string setString:@""];
    }
    //判断输入是/号
    else if(self.num4==4)
    {
        self.num3=self.num2/[self.label.text doubleValue];
        self.label.text=[NSString stringWithFormat:@"%f",self.num3];//计算结果显示出来
        self.num1=[self.label.text doubleValue];//把计算的结果保存一下
        self.num3=0;
        [self.string setString:@""];
    }
}

//当按下清除建时,所有数据清零
-(void)clean:(id)sender{
    [self.string setString:@""];//清空字符串
    self.num3=0;
    self.num2=0;
    self.label.text=@"0";//保证下次输入时清零

}

//返回键
-(void)back:(id)sender
{
    if (![self.label.text isEqualToString:@""])//判断不是空
    {
        [self.string deleteCharactersInRange:NSMakeRange
         ([self.string length]-1,1)];//删除最后一个字符
        self.label.text=[NSString stringWithString:string];//显示结果
    }
}
   
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
5.运行

先出现

IOS小型计算器实例代码

然后点击“OK”

IOS小型计算器实例代码

IOS计算器的实现

阅读数 1787

iOS 减法计算器

阅读数 11

IOS 创建计算器

阅读数 535

IOS加法计算器

阅读数 161

没有更多推荐了,返回首页