ios5--计算器

本文介绍了一个简单的iOS加法计算器应用程序的实现过程。通过使用Swift语言及UIKit框架,文章详细展示了如何设置用户界面元素,如文本框和标签,并实现基本的加法运算逻辑。此外,还介绍了错误处理的方法,确保用户输入有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  ViewController.m
//  01-加法计算器
//
//  首先找main.m文件,然后找AppDelegate,然后找Main Inteferce主交互故事板,然后加载箭头指向的控制器,然后加载控制器内部的View。
//  连线:按住control拖过去然后配置。
//  类扩展:私有的属性和方法。      

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *num1TextField;
@property (weak, nonatomic) IBOutlet UITextField *num2TextField;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.num1TextField.placeholder = @"dddd";
}

- (IBAction)sum {
    // 1. 拿到两个字符串
    NSString *sum1String = self.num1TextField.text;
    NSString *sum2String = self.num2TextField.text;
    
    // 判断
    if (sum1String.length == 0) {
        /*
        // 创建对象
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"输入有误" message:@"请输入第一个数" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        
        // 显示
        [alertView show];
        */
        [self showInfo:@"请输入第一个数"];
        return;
    }
    
    if (sum2String.length == 0) {
        /*
        // 创建对象
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"输入有误" message:@"请输入第二个数" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        
        // 显示
        [alertView show];
        */
        [self showInfo:@"请输入第二个数"];
        return;
    }

    // 2. 把字符串转成数值
    NSInteger sum1 = [sum1String integerValue];
    NSInteger sum2 = [sum2String integerValue];
    
    // 3. 相加
    NSInteger result = sum1 + sum2;
    
    // 4. 显示结果
    self.resultLabel.text = [NSString stringWithFormat:@"%zd", result];}//zd是无符号整型

- (void)showInfo: (NSString *)info{
    // 创建对象
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"输入有误" message:info delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
    
    // 显示
    [alertView show];
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值