概述
重点
iOS中定时器的创建和使用;
为了演示每隔一段时间进行一次View的位置变化和缩放;
示例
演示代码
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.
//添加一个开始button
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn1 setTitle:@"begin" forState:UIControlStateNormal];
btn1.frame = CGRectMake(100, 100, 100, 40);
//添加点击事件
[btn1 addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
//添加一个停止button
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn2 setTitle:@"stop" forState:UIControlStateNormal];
btn2.frame = CGRectMake(100, 200, 100, 40);
//添加点击事件
[btn2 addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
//被移动和缩放的view
UIView *view = [UIView new];
view.frame = CGRectMake(100, 300, 80, 80);
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
//这里为了便于下面代码中获取view实例,用tag(和Android中的用法基本一样);
view.tag = 101;
}
-(void) pressStart
{
NSLog(@"pressStart");
//示例化,并开始定时
//p1:定时器的间隔时间
//p2:委托处理对象
//p3:处理事件
//p4:传递的信息
//p5:循环模式 YES:循环NO:不循环,只触发一次
_timerView = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moveAndScale:) userInfo:@"哈哈哈" repeats:YES];
}
//位移和缩放
-(void) moveAndScale : (NSTimer*) timer
{
NSLog(@"one second later,name = %@",timer.userInfo);
//获取view实例
UIView* view = [self.view viewWithTag:101];
//控制view的缩放和位置
view.frame = CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5, view.frame.size.width+5, view.frame.size.height+5);
}
-(void) pressStop{
NSLog(@"pressStop");
//停止定时
[_timerView invalidate];
}
@end