本字學(xué)習(xí)內(nèi)容:
1.定時器對象的概念
2.定時器對象的創(chuàng)建
3.使用定時器移動視圖
【ViewController.h】
#import<UIkit/UIKit.h>
@interface ViewController:UIViewController{
//定義一個定時器對象
//可以在每隔固定時間發(fā)送一個消息
//通過此消息來調(diào)用相應(yīng)的時間函數(shù)
//通過此函數(shù)可在因定時間段來完成一個時間間的事物
NSTimer *_timerView
}
//定時器的屬性對象
@property(retain,nontomic)NSTimer *timerView
@end
【ViewController.m】
#import "ViewController.m"
@interface viewController()
@end
@implementation ViewController
//屬性和成員變量同步
@systhesise timerView=_timerView
-(void)viewDidLoad{
[super viewDidLoad];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.fram=CGRectMake(100,100,80,40);
[btn setTitle:@"啟動定時器" forState:UIControlSateNormal];
[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:UIControlSateNorma];
btnStop add|Target: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];
//設(shè)置View的標(biāo)簽值
//通過父視圖對象以及view的標(biāo)簽值可以獲得相應(yīng)的視圖對象
view.tag=101
}
//按下開始按鈕時調(diào)用
-(void)pressStart
{
//通過NSTimer的類方法創(chuàng)建一個定時器并且啟動這個定時器
//P1:每隔多長時間調(diào)用定時器函數(shù),以秒為單位(scheduledTimerWithTimeInterval:1)
//P2:表示實(shí)現(xiàn)定時器函數(shù)的對象(target:self)
//P3:定時器函數(shù)對象( selector:@selector(updateTime))
//P4:可以定時器器函數(shù)中一個參數(shù)跪者,無參數(shù)可以傳nil(userInfo:nil)
//P5:定時器是否重復(fù)操作YES為重得棵帽,NO只完成一次函數(shù)調(diào)用(repeats:NO)
//返回值為一個新那的定時器對象
//不帶參數(shù)
//_timerView=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:NO];
//帶參數(shù)
_timerView=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:@"小明" repeats:NO];
}
//定時器函數(shù)
//不帶參數(shù)
/*-(void) updateTimer{
NSLog(@"test!!");
//點(diǎn)擊‘啟動定時器’時輸出:test!! (每隔一分鐘打印一次)
}*/
//帶參數(shù),可以將定時器本身做為參數(shù)傳入
-(void) updateTimer:(NSTimer *) timer{
NSLog(@"test!! name=%@",timer.userInfo);
//點(diǎn)擊‘啟動定時器’時輸出:test!! name=小明 (每隔一分鐘打印一次)
//最好tag從100開始
UIView *view=[self.view viewWithTag:101];
//將視圖移動5個像素渣玲,移動卡盾原因scheduledTimerWithTimeInterval:1值太大
view.rame=CGRectMake(view.frame.origin.x+5,view.frame.origin.y+5);
}
//按下停止按鈕調(diào)用
-(void)pressStop
{
if(_timeView !=nil){
//停止定時器
[_timerView invalidate];
}