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