NStimer 倒计时实现

1、思路:当点击UIswich控件的开启功能时,再开始执行一个倒计时功能的实现,关闭了UIswich控件,则不再执行倒计时功能。

2、代码实现:

//
//  ViewController.m
//  NStimer
//
//  Created by rimi on 15/11/11.
//  Copyright © 2015年 Liu. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    int secondsCountDown;//倒计时总时长
    NSTimer *countDownTimer;//计时器
    UILabel *labelText;//显示秒数
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    labelText = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 120, 30)];
    [self.view addSubview:labelText];
    
    UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 300, 120, 30)];
    [theSwitch addTarget:self
                  action:@selector(switchToChange:)
        forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:theSwitch];
    
    secondsCountDown = 10;//设置秒数
}

- (void)timeFireMethod
{
    //倒计时减1
    secondsCountDown--;
    //修改倒计时便签显示内容
    labelText.text = [NSString stringWithFormat:@"%d",secondsCountDown];
    //当倒计时到0时,打印倒倒计时结束
    if (secondsCountDown == 0) {
        [countDownTimer invalidate];/**< 时间无效  */
         [labelText removeFromSuperview];/**< 移除显示  */
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                       message:@"您应该记账了!"
                                                                       preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction    *action = [UIAlertAction
                                 actionWithTitle:@"确定"
                                           style:UIAlertActionStyleDefault
                                         handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
//        NSLog(@"倒计时结束");
    }
}
//监听UISwitch事件
- (void)switchToChange:(UISwitch*)sender
{
    
    if (sender.isOn) {
        
        countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                          target:self
                                                          selector:@selector(timeFireMethod)
                                                          userInfo:nil
                                                          repeats:YES];
        labelText.text = [NSString stringWithFormat:@"%d",secondsCountDown];
        secondsCountDown = 10;
        [self timeFireMethod];
        [self.view addSubview:labelText];
    }
    else
    {
        [countDownTimer invalidate];
        [labelText removeFromSuperview];
        NSLog(@"已关闭计时");
    }
}

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值