ViewController.m
// ViewController.m
// 定时器和视图移动
//
// Created by mac on 2016/10/27.
// Copyright © 2016年 mac. All rights reserved.
//
#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 = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100,100, 100,40);
[btn setTitle:@"启动定时器"forState:UIControlStateNormal];
[btn addTarget:selfaction:@selector(pressStart)forControlEvents:UIControlEventTouchUpInside ];
[self.viewaddSubview:btn];
// 定时器停止按钮
UIButton* btnStop = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
btnStop.frame = CGRectMake(100,200, 100,40);
[btnStop setTitle:@"停止定时器"forState:UIControlStateNormal];
[btnStop addTarget:selfaction:@selector(pressStop)forControlEvents:UIControlEventTouchUpInside ];
[self.viewaddSubview:btnStop];
UIView* view = [[UIViewalloc] init];
view.backgroundColor = [UIColorredColor];
view.frame=CGRectMake(0,0, 80,80);
[self.viewaddSubview:view];
view.tag = 101;
}
// 按下开始按钮
-(void)pressStart
{
// 通过NSTimer的类方法创建一个定时器并且启动一个定时器
// p1:每隔多长时间调用定时器函数,以秒为单位
// p2:表示实现定时器函数的对象(指针)
// p3:定时器函数对象
// p4:可以传入定时器函数中一个参数,无参数可以传nil
// p5:定时器是否重复操作YES为重复,NO只完成一次操作
// 返回值为一个新建好的定时器对象
_timerView=[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(updateTimer:)userInfo:@"xiaom"repeats:YES];
}
// 定时器参数
// 可以将定时器本身作为参数传入
-(void)updateTimer:(NSTimer*)timer
{
NSLog(@"Test!!! name = %@",timer.userInfo);
UIView* view =[self.viewviewWithTag:101];
view.frame = CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5,80, 80);
}
// 按下停止按钮
-(void)pressStop
{
if (_timerView !=nil) {
[_timerView invalidate];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController.h
// ViewController.h
// 定时器和视图移动
//
// Created by mac on 2016/10/27.
// Copyright © 2016年 mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
// 私有的内部使用
// 定义一个定时器对象(成员变量)
// 可以在每隔固定时间发送一个消息
// 通过此消息调用相应的时间函数
// 通过此函数可以在固定是假段来完成一个根据时间间隔的任务
NSTimer* _timerView;
}
// 定时器的属性对象(属性)
// 公有的外部部使用
@property (retain,nonatomic)NSTimer* timerView ;
@end