1.定时器对象的概念
2.定时器对象的创建
3.使用定时器移动视图
ViewController.h文件的声明:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
//先声明一个定时器对象
//可以在每隔固定的时间发送一个消息,通过此消息来调用相应的事件函数
//通过此函数可以在固定时间段来完成一个根据时间 间隔的任务
NSTimer * _timerView;
}
//定时器的属性对象
@property(strong,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.
//buttonWithType:类型为圆角按钮
//启动定时器按钮
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置位置
btn.frame = CGRectMake(100, 100, 80, 40);
//XCODE有个特点 输入中文以后 后面就不会再有提示了
//如果想要出提示,那么中文先不要出,打完该打完的话 再输中文
[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
{
//启动一个定定时器
//参数scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>
//通过NSTimer的类方法创建一个定时器并且启动
//P1:每隔多长时间调用定时器函数 秒为单位 1秒后启动
//P2:表示实现定时器函数的对象
//P3:定时器函数 通过selector把对象名封装成函数对象,将来程序会查找这个函数对象
//P4:可以传入定时器函数中,一个参数 作为辅助用,无参数 可以传空
//P5:定时器是否重复操作 比如定个闹钟 半个小时响一次,响完之后需再设定,就不需要重复
//点击一次 每隔1秒种都会打印 test!!
//返回值为一个新建好的定时器对象
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:@"小明" repeats:YES];
//注意有参数后 updateTimer: 带冒号
//通过viewWithTag 访问 view tag最好从100开始
UIView * view = [self.view viewWithTag:101];
//通过这样 启动定时器时,每打印一次 定时器都会移动5个像素
//如果想要流畅一些 无延迟 就在scheduledTimerWithTimeInterval:0.1 时间设置短一些,
//view.frame.origin.x+1 移动距离短一些
view.frame = CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5, 80, 80);
}
//定时器函数
- (void)updateTimer:(NSTimer *)timer
{
//userInfo可为任意类型
NSLog(@"test!!! name = %@",timer.userInfo);
}
//按下停止按钮时调用 得知道停止哪一个定时器
- (void)pressStop
{
if ( _timerView != nil ){
//停止定时器
[_timerView invalidate];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end