NSTimer与运行循环

NSTimer使用详解

NSTimer准确吗?如果不准确,怎么办?

通常用来有一点时间跨度的周期性事件的处理! CDADisplayLink

 

 1 //
 2 //  HMViewController.m
 3 //  08-倒计时
 4 //
 5 //  Created by apple on 14-8-18.
 6 //  Copyright (c) 2014年 itcast. All rights reserved.
 7 //
 8 
 9 #import "HMViewController.h"
10 
11 @interface HMViewController () <UIAlertViewDelegate>
12 
13 @property (weak, nonatomic) IBOutlet UILabel *counterLabel;
14 
15 @property (nonatomic, strong) NSTimer *timer;
16 @end
17 
18 @implementation HMViewController
19 
20 /** 开始 */
21 - (IBAction)start
22 {
23     // 倒计时10秒,每秒更新一下Label的显示
24     // 计时器
25     /** 
26      参数说明 
27      1. 时间间隔,double
28      2. 监听时钟触发的对象
29      3. 调用方法
30      4. userInfo,可以是任意对象,通常传递nil
31      5. repeats:是否重复
32      */
33     self.counterLabel.text = @"10";
34     
35     // scheduledTimerWithTimeInterval 方法本质上就是创建一个时钟,
36     // 添加到运行循环的模式是DefaultRunLoopMode
37     // ----------------------------------------------
38     // 1>
39 //    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:@"hello timer" repeats:YES];
40     
41     // ----------------------------------------------
42     // 2> 与1等价
43 //    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
44 //    // 将timer添加到运行循环
45 //    // 模式:默认的运行循环模式
46 //    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
47     
48     // ----------------------------------------------
49     // 3>
50     self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
51     // 将timer添加到运行循环
52     // 模式:NSRunLoopCommonModes的运行循环模式(监听滚动模式)
53     [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
54     //[self updateTimer:self.timer];
55 }
56 
57 /** 时钟更新方法 */
58 - (void)updateTimer:(NSTimer *)timer
59 {
60    // NSLog(@"%s", __func__);
61     // 1. 取出标签中的数字
62     int counter = self.counterLabel.text.intValue;
63     
64     // 2. 判断是否为零,如果为0,停止时钟
65     if (--counter < 0) {
66         // 停止时钟
67         [self pause];
68         
69         // 提示用户,提示框
70 //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"开始" message:@"开始啦......" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", @"哈哈", nil];
71 //
72 //        [alert show];
73         [[[UIAlertView alloc] initWithTitle:@"开始" message:@"开始啦......" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", @"哈哈", nil] show];
74     } else {
75         // CTRL + I
76         // 3. 修改数字并更新UI
77         self.counterLabel.text = [NSString stringWithFormat:@"%d", counter];
78     }
79 }
80 
81 /** 暂停 */
82 - (IBAction)pause
83 {
84     // 停止时钟,invalidate是唯一停止时钟的方法
85     // 一旦调用了invalidate方法,timer就无效了,如果再次启动时钟,需要重新实例化
86     [self.timer invalidate];
87 }
88 
89 #pragma mark - alertView代理方法
90 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
91 {
92     NSLog(@"%ldaaa-------", (long)buttonIndex);
93 }
94 
95 @end

 

  1 //
  2 //  HMViewController.m
  3 //  09-图片轮播器
  4 //
  5 //  Created by apple on 14-8-18.
  6 //  Copyright (c) 2014年 itcast. All rights reserved.
  7 //
  8 
  9 #import "HMViewController.h"
 10 
 11 #define kImageCount     5
 12 
 13 @interface HMViewController () <UIScrollViewDelegate>
 14 @property (nonatomic, strong) UIScrollView *scrollView;
 15 @property (nonatomic, strong) UIPageControl *pageControl;
 16 
 17 @property (nonatomic, strong) NSTimer *timer;
 18 @end
 19 
 20 @implementation HMViewController
 21 
 22 - (UIScrollView *)scrollView
 23 {
 24     if (_scrollView == nil) {
 25         _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 20, 300, 130)];
 26         _scrollView.backgroundColor = [UIColor redColor];
 27         
 28         [self.view addSubview:_scrollView];
 29         
 30         // 取消弹簧效果
 31         _scrollView.bounces = NO;
 32         
 33         // 取消水平滚动条
 34         _scrollView.showsHorizontalScrollIndicator = NO;
 35         _scrollView.showsVerticalScrollIndicator = NO;
 36         
 37         // 要分页
 38         _scrollView.pagingEnabled = YES;
 39         
 40         // contentSize
 41         _scrollView.contentSize = CGSizeMake(kImageCount * _scrollView.bounds.size.width, 0);
 42         
 43         // 设置代理
 44         _scrollView.delegate = self;
 45     }
 46     return _scrollView;
 47 }
 48 
 49 - (UIPageControl *)pageControl
 50 {
 51     if (_pageControl == nil) {
 52         // 分页控件,本质上和scrollView没有任何关系,是两个独立的控件
 53         _pageControl = [[UIPageControl alloc] init];
 54         // 总页数
 55         _pageControl.numberOfPages = kImageCount;
 56         // 控件尺寸
 57         CGSize size = [_pageControl sizeForNumberOfPages:kImageCount];
 58         
 59         _pageControl.bounds = CGRectMake(0, 0, size.width, size.height);
 60         _pageControl.center = CGPointMake(self.view.center.x, 130);
 61         
 62         // 设置颜色
 63         _pageControl.pageIndicatorTintColor = [UIColor redColor];
 64         _pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
 65         
 66         [self.view addSubview:_pageControl];
 67         
 68         // 添加监听方法
 69         /** 在OC中,绝大多数"控件",都可以监听UIControlEventValueChanged事件,button除外" */
 70         [_pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
 71     }
 72     return _pageControl;
 73 }
 74 
 75 // 分页控件的监听方法
 76 - (void)pageChanged:(UIPageControl *)page
 77 {
 78     NSLog(@"%d", page.currentPage);
 79     
 80     // 根据页数,调整滚动视图中的图片位置 contentOffset
 81     CGFloat x = page.currentPage * self.scrollView.bounds.size.width;
 82     [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
 83 }
 84 
 85 // 视图加载完成调用,通常用来设置数据
 86 - (void)viewDidLoad
 87 {
 88     [super viewDidLoad];
 89 
 90     // 设置图片
 91     for (int i = 0; i < kImageCount; i++) {
 92         NSString *imageName = [NSString stringWithFormat:@"img_%02d", i + 1];
 93         UIImage *image = [UIImage imageNamed:imageName];
 94         
 95         UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.scrollView.bounds];
 96         imageView.image = image;
 97         
 98         [self.scrollView addSubview:imageView];
 99     }
100     
101     // 计算imageView的位置
102     [self.scrollView.subviews enumerateObjectsUsingBlock:^(UIImageView *imageView, NSUInteger idx, BOOL *stop) {
103         
104         // 调整x => origin => frame
105         CGRect frame = imageView.frame;
106         frame.origin.x = idx * frame.size.width;
107         
108         imageView.frame = frame;
109     }];
110 //    NSLog(@"%@", self.scrollView.subviews);
111     
112     // 分页初始页数为0
113     self.pageControl.currentPage = 0;
114     
115     // 启动时钟
116     [self startTimer];
117 }
118 
119 - (void)startTimer
120 {
121     self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
122     // 添加到运行循环
123     [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
124 }
125 
126 - (void)updateTimer
127 {
128     // 页号发生变化
129     // (当前的页数 + 1) % 总页数
130     int page = (self.pageControl.currentPage + 1) % kImageCount;
131     self.pageControl.currentPage = page;
132     
133     NSLog(@"%d", self.pageControl.currentPage);
134     // 调用监听方法,让滚动视图滚动
135     [self pageChanged:self.pageControl];
136 }
137 
138 #pragma mark - ScrollView的代理方法
139 // 滚动视图停下来,修改页面控件的小点(页数)
140 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
141 {
142     // 停下来的当前页数
143     NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
144     
145     // 计算页数
146     int page = scrollView.contentOffset.x / scrollView.bounds.size.width;
147     
148     self.pageControl.currentPage = page;
149 }
150 
151 /**
152  修改时钟所在的运行循环的模式后,抓不住图片
153  
154  解决方法:抓住图片时,停止时钟,送售后,开启时钟
155  */
156 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
157 {
158     NSLog(@"%s", __func__);
159     // 停止时钟,停止之后就不能再使用,如果要启用时钟,需要重新实例化
160     [self.timer invalidate];
161 }
162 
163 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
164 {
165     NSLog(@"%s", __func__);
166     [self startTimer];
167 }
168 
169 
170 @end

 

转载于:https://www.cnblogs.com/liqiantu/p/4393369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值