本项目是取自传智播客的教学项目,加入笔者的修改和润饰。
1. 项目名称:倒计时时钟
2. 项目截图展示
3. 项目功能
- 点击播放按钮,倒计时开始。
- 点击暂停按钮,倒计时暂停。再点击播放按钮,倒计时继续。
- 倒计时时钟运行时,可以滚动textView的滚动条。
4. 项目代码
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,weak) IBOutlet UILabel *counterLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, copy) NSString *startNum;
@end
@implementation ViewController
- (void) setStartNum:(NSString *)startNum
{
//设定标签初始状态显示的数字
_startNum = @"10";
self.counterLabel.text = _startNum;
}
//开始倒计时
- (IBAction)start
{
//NSTimer的设定
self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
// 将timer添加到运行循环
// 模式:NSRunLoopCommonModes的运行循环模式(监听滚动模式)
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//[self updateTimer:self.timer];
}
/** 时钟更新方法 */
- (void)updateTimer:(NSTimer *)timer
{
// 1. 取出标签中的数字
int counter = self.counterLabel.text.intValue;
// 2. 判断是否为零,如果为0,停止时钟
if (--counter < 0) {
// 暂停时钟
[self pause];
// 提示用户,提示框
[[[UIAlertView alloc] initWithTitle:@"时钟结束" message:@"结束" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", @"添加按钮", nil] show];
} else {
// 3. 修改数字并更新UILabel显示的内容
self.counterLabel.text = [NSString stringWithFormat:@"%d", counter];
}
}
//暂停时钟
- (IBAction)pause
{
// 停止时钟,invalidate是唯一停止时钟的方法
// 一旦调用了invalidate方法,timer就无效了,如果再次启动时钟,需要重新实例化
[self.timer invalidate];
}
#pragma mark - alertView代理方法
//监听点击了哪个按钮,并输出
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"%ld", (long)buttonIndex);
}
@end
5. 本项目必须掌握的代码段
- 启动时钟
//NSTimer的设定
self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}
- 将时钟添加到运行循环
// 模式:NSRunLoopCommonModes的运行循环模式(监听滚动模式)
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
- 警告框
[[[UIAlertView alloc] initWithTitle:@"时钟结束" message:@"结束" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", @"添加按钮", nil] show];
6. 笔记
scheduledTimerWithTimeInterval 方法本质上就是创建一个时钟,
添加到运行循环的模式是DefaultRunLoopMode
代码:
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:@"hello timer" repeats:YES];
等价于:
self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];