本示例实现的动画: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];
}