以下是我在 Xcode 中使用 Objective C 制作的应用程序。这是 ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
valueString = @"";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)tappedClear:(id)sender
{
total = 0;
valueString = @"";
label.text = @"0";
}
-(IBAction)tappedNumber:(UIButton*)btn
{
int num = btn.tag;
if (num == 0 && total == 0) {
return;
}
if (lastButtonWasMade) {
lastButtonWasMade = false;
valueString = @"";
}
NSString *numAsString = [NSString stringWithFormat:@"%i",num];
valueString = [valueString stringByAppendingString:numAsString];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *n = [formatter numberFromString:valueString];
label.text = [formatter stringFromNumber:n];
if (total == 0) {
total = [valueString intValue];
}
}
-(IBAction)tappedPlus:(id)sender
{
[self setMode:1];
}
-(IBAction)tappedMinues:(id)sender
{
[self setMode:-1];
}
-(IBAction)tappedEquals:(id)sender
{
if (mode == 0) {
return;
}
if (mode == 1) {
total +=[valueString intValue];
}
if (mode == -1) {
total -=[valueString intValue];
}
if (mode == 2) {
total *=[valueString intValue];
}
if (mode == 1/2) {
total /=[valueString intValue];
}
if (mode == 10) {
total *=[valueString intValue];
}
valueString = [NSString stringWithFormat:@"%i",total];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *n = [formatter numberFromString:valueString];
label.text = [formatter stringFromNumber:n];
mode = 0;
}
-(IBAction)tappedMultiply:(id)sender
{
[self setMode:2];
}
-(IBAction)tappedDivide:(id)sender
{
[self setMode:1/2];
}
-(IBAction)tappedDecimal:(id)sender
{
}
-(IBAction)tappedPercent:(id)sender
{
[self setMode:10];
}
-(void)setMode:(int)m
{
if (total == 0) {
return;
}
mode = m;
lastButtonWasMade = true;
total = [valueString intValue];
}
@end
以下是我的 ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
int total;
int mode;
NSString *valueString;
IBOutlet UILabel *label;
BOOL lastButtonWasMade;
}
-(IBAction)tappedClear:(id)sender;
-(IBAction)tappedNumber:(UIButton*)btn;
-(IBAction)tappedPlus:(id)sender;
-(IBAction)tappedMinues:(id)sender;
-(IBAction)tappedEquals:(id)sender;
-(IBAction)tappedMultiply:(id)sender;
-(IBAction)tappedDivide:(id)sender;
-(IBAction)tappedDecimal:(id)sender;
-(IBAction)tappedPercent:(id)sender;
@end
我在 Main.storyboard 中标记了每个按钮,以消除多余的代码。基本上,我想要一个可以工作的小数按钮、一个可以工作的百分比按钮和一个可以工作的除法按钮。我还想在按下等号后输入新数字时清除屏幕。
我会导入图片,但我没有声望。a