IOS開發(fā) 定時器和視圖移動

本字學習內容:

1.定時器對象的概念

2.定時器對象的創(chuàng)建

3.使用定時器移動視圖


【ViewController.h】

#import<UIkit/UIKit.h>

@interface ViewController:UIViewController{

//定義一個定時器對象

//可以在每隔固定時間發(fā)送一個消息

//通過此消息來調用相應的時間函數

//通過此函數可在因定時間段來完成一個時間間的事物

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];

//設置View的標簽值

//通過父視圖對象以及view的標簽值可以獲得相應的視圖對象

view.tag=101

}


//按下開始按鈕時調用

-(void)pressStart
{

//通過NSTimer的類方法創(chuàng)建一個定時器并且啟動這個定時器

//P1:每隔多長時間調用定時器函數,以秒為單位(scheduledTimerWithTimeInterval:1)

//P2:表示實現定時器函數的對象(target:self)

//P3:定時器函數對象( selector:@selector(updateTime))

//P4:可以定時器器函數中一個參數,無參數可以傳nil(userInfo:nil)

//P5:定時器是否重復操作YES為重得,NO只完成一次函數調用(repeats:NO)

//返回值為一個新那的定時器對象

//不帶參數

//_timerView=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:NO];


//帶參數

_timerView=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:@"小明" repeats:NO];

}


//定時器函數

//不帶參數

/*-(void) updateTimer{

NSLog(@"test!!");

//點擊‘啟動定時器’時輸出:test!! (每隔一分鐘打印一次)

}*/


//帶參數,可以將定時器本身做為參數傳入

-(void) updateTimer:(NSTimer *) timer{

NSLog(@"test!! name=%@",timer.userInfo);

//點擊‘啟動定時器’時輸出: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);

}


//按下停止按鈕調用

-(void)pressStop
{

if(_timeView !=nil){

//停止定時器

[_timerView invalidate];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容