此文学习来源为:http://study.163.com/course/introduction/1002858003.htm
此工程文件实现功能:
1、通过点击“启动定时器”按钮,在定时器方法中每隔固定时长打印字符串,并实现view视图移动
2、通过点击“停止定时器”按钮,停止定时器方法的执行
3、以上操作可以重复执行
===========================ViewController.h脚本==============================
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
//定义一个定时器对象
//可以在每个固定时间发送一个消息
//通过此消息来调用相应的时间函数
//通过此函数可以在固定时间段来完成一个根据时间间隔的任务
NSTimer* _timerView;
}
//定时器的属性对象
@property (retain,nonatomic) NSTimer* timerView;
@end
===========================ViewController.m脚本==============================
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
//属性和成员变量的同步
@synthesize timerView = _timerView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 80, 40);
[btn setTitle:@"启动定时器" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
UIButton* btnStop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnStop.frame = CGRectMake(100, 200, 80, 40);
[btnStop setTitle:@"停止定时器" forState:UIControlStateNormal];
[btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnStop];
UIView* view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, 80, 80);
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
//通过view的标签值
//通过父亲视图对象以及view的标签值可以获得相应的视图对象
view.tag = 101;
}
//按下开始按钮时调用
-(void)pressStart
{
//NSTimer的类方法创建一个定时器并且启动这个定时器
//P1:每隔多长时间调用定时器函数,以秒为单位
//P2:表示实现定时器函数的对象(指针)
//P3:定时器函数对象
//P4:可以传入定时器函数中一个参数,无参数可以传nil
//P5:定时器是否重复操作 YES:重复 NO:只完成一次函数调用
//返回值为一个新建好的定时器对象
_timerView = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTimer:) userInfo:@"小明" repeats:YES];
}
-(void) updateTimer:(NSTimer*) timer
{
NSLog(@"test!!!,name = %@",timer.userInfo);
//最好tag从100开始
UIView* view = [self.view viewWithTag:101];
view.frame = CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, 80, 80);
}
//按下停止按钮时调用
-(void)pressStop
{
if (_timerView != nil) {
//停止定时器
[_timerView invalidate];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
学习总结:
- 重点:定时器的创建使用
- 难点:定时器移动视图
源码链接地址:https://pan.baidu.com/s/1yrOLXZZeu9MiOWtMq5-EGA 密码:7t1l