#import "ViewController.h"
@interface ViewController ()
@property(retain)UILabel* resultLabel;
@property(retain)NSString* firstNum;
@property(retain)NSString* secondNum;
@property(retain)NSString* sybolStr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_resultLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 20, 320, 100)];
_resultLabel.backgroundColor=[UIColor lightGrayColor];
[self.view addSubview:_resultLabel];
NSArray* titleArr=@[@"1",@"2",@"3",@"+",@"4",@"5",@"6",@"-",@"7",@"8",@"9",@"*",@"0",@"AC",@"/",@"="];
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(10*(j+1)+60*j, 120+20*(i+1)+60*i, 60, 60);
btn.backgroundColor=[UIColor greenColor];
[btn setTitle:titleArr[i*4+j] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
}
}
-(void)btnAction:(UIButton*)sender
{
if ([sender.currentTitle isEqualToString:@"+"]||[sender.currentTitle isEqualToString:@"-"]||[sender.currentTitle isEqualToString:@"*"]||[sender.currentTitle isEqualToString:@"/"]) {
_firstNum=_resultLabel.text;
_resultLabel.text=@"";
_sybolStr=sender.currentTitle;
}else if ([sender.currentTitle isEqualToString:@"AC"]){
_resultLabel.text=@"";
}else if ([sender.currentTitle isEqualToString:@"="]){
_secondNum=_resultLabel.text;
[self jisuan];
}else{
if (_resultLabel.text.length==0) {
_resultLabel.text=sender.currentTitle;
}else
_resultLabel.text=[NSString stringWithFormat:@"%@%@",_resultLabel.text,sender.currentTitle];
}
}
-(void)jisuan
{
if([_sybolStr isEqualToString:@"+"]){
NSInteger result;
result=[_firstNum integerValue]+[_secondNum integerValue];
_resultLabel.text=[NSString stringWithFormat:@"%ld",(long)result];
//_firstNum=_resultLabel.text;
}
}
@end
简单计算器(OC)
最新推荐文章于 2024-07-31 10:34:18 发布