標籤:
定時器UITimer和視圖對象移動
在ViewController.h
#import <UIKit/UIKit.h>@interface ViewController : UIViewController{ //定義一個定時器對象 //可以在每隔固定的時間發送一個訊息 //通過訊息來調用相應的事件函數 //通過此函數可在固定時間段來完成一個根據時間間隔的任務 NSTimer * _timeView;}//定時器的屬性對象@property(retain,nonatomic) NSTimer * timeView;@end
在ViewController.m
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController//屬性和成員變數的同步@synthesize timeView =_timeView;- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //啟動定時器按鈕 UIButton * btn =[UIButton buttonWithType:UIButtonTypeRoundedRect]; //目前我們使用UIButtonTypeRoundedRect設定圓角已經不可以了,需要加上下面2句設定四周的圓角 [btn.layer setMasksToBounds:YES]; [btn.layer setCornerRadius:10.0];//設定矩形四個圓角半徑 btn.frame=CGRectMake(100, 100, 100, 40); [btn setTitle:@"定時器按鈕" forState:UIControlStateNormal]; btn.backgroundColor=[UIColor greenColor]; [btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; //停止定時器按鈕 UIButton * btnStop =[UIButton buttonWithType:UIButtonTypeRoundedRect]; //目前我們使用UIButtonTypeRoundedRect設定圓角已經不可以了,需要加上下面2句設定四周的圓角 [btnStop.layer setMasksToBounds:YES]; [btnStop.layer setCornerRadius:10.0];//設定矩形四個圓角半徑 btnStop.frame=CGRectMake(100, 200, 100, 40); [btnStop setTitle:@"停止定時器" forState:UIControlStateNormal]; btnStop.backgroundColor=[UIColor redColor]; [btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btnStop]; //建立一個view視圖 UIView * view =[[UIView alloc]init]; view.frame =CGRectMake(0, 0, 80, 80); view.backgroundColor=[UIColor orangeColor]; [self.view addSubview:view]; //設定view的標籤值 //通過父親視圖對象以及view的標籤值可以獲得相應的視圖對象 view.tag=101;}//按下開始按鈕函數- (void) pressStart{ //NSTime的類方法建立一個定時器並且啟動這個定時器 //p1:每個多長時間調用定時器函數,以秒為單位 //p2:表示實現這個定時器函數的對象 //p3:定時器函數對象 //p4:可以傳入定時器函數中一個參數,無參數傳入nil //p5:定時器是否重複操作YES表示重複,NO表示只完成一次函數調用// _timeView = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; _timeView = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(updateTime:) userInfo:@"蘋果" repeats:YES];}//定時器函數//- (void) updateTime{// NSLog(@"test11");//}//將定時器本身作為參數傳入- (void) updateTime:(NSTimer* )timer{ NSLog(@"test11 name=%@",timer.userInfo); //最好tag從100開始,避免衝突 UIView * view =[self.view viewWithTag:101]; view.frame=CGRectMake(view.frame.origin.x+1,view.frame.origin.y+1, 80, 80);}//按下停止按鈕函數- (void) pressStop{ //停止定時器 if(_timeView!=nil){ [_timeView invalidate]; }}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
iOS開發從入門到精通--定時器UITimer和視圖對象移動