我们先声明一个定时器:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController //私有 { //定义一个定时器对象 //可以在固定时间内发送一个消息,通过消息来调用响应的函数. //通过此函数可以在固定的时间段完成一个任务 NSTimer* _timerView; } //共有 @property (nonatomic, strong) NSTimer *timerView; @end
创建按钮并添加按钮事件:
#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. self.view.backgroundColor = [UIColor blackColor]; //创建一个启动按钮 UIButton *btnStart = [UIButton buttonWithType:UIButtonTypeCustom]; btnStart.frame = CGRectMake(100, 100, 100, 100); [btnStart setTitle:@"启动定时器" forState:UIControlStateNormal]; [self.view addSubview:btnStart]; //添加开始定时器按钮事件 [btnStart addTarget:self action:@selector(btnStart:) forControlEvents:UIControlEventTouchUpInside]; //创建一个停止按钮 UIButton *btnStop = [UIButton buttonWithType:UIButtonTypeCustom]; btnStop.frame = CGRectMake(100, 300, 100, 100); [btnStop setTitle:@"停止定时器" forState:UIControlStateNormal]; [self.view addSubview:btnStop]; //添加停止定时器按钮事件 [btnStop addTarget:self action:@selector(btnStopAct:) forControlEvents:UIControlEventTouchUpInside]; //创建一个View UIView *view = [[UIView alloc]init]; view.frame = CGRectMake(0, 0, 80, 80); view.backgroundColor = [UIColor whiteColor]; //可以通过父视图对象以及view的标签值,可以获得相应的视图对象 view.tag = 101; [self.view addSubview:view]; } - (void)btnStart:(UIButton *)btn{ //通过类方法创建一个定时器并启动 //p1.每隔多长事件调用此函数. //p2.实现定时器函数的对象(指针) //p3.定时器函数对象 //p4.可以传入一个参数,无参传nil;(类型是id) //p5.定时器是否重复调用 //返回值为一个新建好的定时器对象 _timerView = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updataTimer:) userInfo:@"小明" repeats:YES]; } //停止定时器 - (void)btnStopAct:(UIButton *)btn{ //停止定时器 [_timerView invalidate]; _timerView = nil; } //定时器函数 - (void)updataTimer:(NSTimer *)timerstart{ //根据view.tag值获取对应的视图对象 UIView *view = [self.view viewWithTag:101]; view.frame = CGRectMake(view.frame.origin.x +5, view.frame.origin.y + 5, 80, 80); }