1. 程式人生 > >ios-計時器示範:一閃一閃View(動畫效果)

ios-計時器示範:一閃一閃View(動畫效果)

本示例實現的動畫:UIView定時消失隨後又閃現,即一閃一閃的動畫

所採用的技術:定時器(NSTimer) + 動畫(beginAnimations/commitAnimations)

具體實現步驟:

1、在.h檔案中定義一個變數和一個Method:

2、在.m檔案中開啟與關閉定時器,以及繫結Method:

3、啟動計時器:

第二步:動畫部分

在handleScollTimer:方法中寫動畫程式碼:

#import "FlashViewController.h"

@interface FlashViewController ()
{
    NSTimer *showTimer;//計時器變數
UIView * scanLine; } ////要執行的方法 //-(void)handleScrollTimer:(NSTimer *)theTimer; -(void)startTimer; @end @implementation FlashViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor whiteColor]; scanLine = [[UIView
alloc] initWithFrame:CGRectMake(100, 100, 50, 50)]; scanLine.backgroundColor = [UIColor blueColor]; [self.view addSubview:scanLine]; //開啟執行緒 [self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.
} - (void)viewDidAppear:(BOOL)animated { ///頁面顯示完畢的時候執行 //重新開啟定時器 [showTimer setFireDate:[NSDate distantPast]]; } -(void)startTimer { //定義時間計數器:每隔2秒執行一次handleScrollTimer方法 showTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(handleScrollTimer:) userInfo:nil repeats:true]; [[NSRunLoop currentRunLoop] addTimer:showTimer forMode:NSDefaultRunLoopMode]; } ///頁面消失完畢的時候執行 -(void)viewDidDisappear:(BOOL)animated { //關閉定時器 [showTimer setFireDate:[NSDate distantFuture]]; } -(void)handleScrollTimer:(NSTimer *)theTimer { scanLine.alpha = 1.0; [UIView beginAnimations:@"scanLine" context:nil]; [UIView setAnimationDuration:0.8]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; scanLine.alpha = 0.05; [UIView commitAnimations]; }