Fork me on GitHub

进球弹出提醒效果

最近研究UIView动画,对比分在线客户端使用了很多UIView动画效果。 

 

一直以来都是使用UIView animateWithDuration实现UIView动画,但是这种模式无法实现连续动,每个UIView只能同步播放,由于刚接触iOS开发,一直找不到解决方法,网上找了许多都是使用CAKeyframeAnimation来实现,虽然CAKeyframeAnimation网上实现起来更简单,但我觉得还是有点麻烦。于是自己扩展了UIView实现连续动画,就是一段动画运行完毕后调用另一段动画,保证两段动画没有重叠。 

大概有两种方法可以选择: 
1.增加延迟以便在第一段动画结束之后在启动第二段动画([performSelector:withObject:afterDelay:]) 

2.指定动画委托回调(animationDidStop:finished:context:) 

从编程的角度来说就更容易,下面我们将扩展类UIView的方法,通过类别引入一个新的方法----commitModalAnimations.调用此方法而不是调用commitAnimations方法,它会建立一个新的runloop,该循环只有在动画结束的时候才会停止。这样确保了commitModalAnimations方法只有在动画结束才将控制权返还给调用方法,利用此扩展方法可以将动画块按顺序放进代码中,不必做任何其他的修改就能避免动画的重叠现象。 

Objective-c代码 
  1. @interface UIView (ModalAnimationHelper)  
  2. + (void) commitModalAnimations;  
  3. @end  
  4.   
  5.   
  6.   
  7. @interface UIViewDelegate : NSObject  
  8. {  
  9.     CFRunLoopRef currentLoop;  
  10. }  
  11. @end  



Objective-c代码 
  1. @implementation UIViewDelegate  
  2. -(id) initWithRunLoop: (CFRunLoopRef)runLoop   
  3. {  
  4.     if (self = [super init]) currentLoop = runLoop;  
  5.     return self;  
  6. }  
  7.   
  8. -(void) animationFinished: (id) sender  
  9. {  
  10.     CFRunLoopStop(currentLoop);  
  11. }  
  12. @end  
  13.   
  14. @implementation UIView (ModalAnimationHelper)  
  15. + (void) commitModalAnimations  
  16. {  
  17.     CFRunLoopRef currentLoop = CFRunLoopGetCurrent();  
  18.       
  19.     UIViewDelegate *uivdelegate = [[UIViewDelegate alloc] initWithRunLoop:currentLoop];  
  20.     [UIView setAnimationDelegate:uivdelegate];  
  21.     [UIView setAnimationDidStopSelector:@selector(animationFinished:)];  
  22.     [UIView commitAnimations];  
  23.     CFRunLoopRun();  
  24.     [uivdelegate release];  
  25. }  
  26. @end  



以后这样调用就可以了: 

Objective-c代码 
  1. -(void) displayAnimate{   
  2.     self.alpha = 1;  
  3.     CGRect _frame = self.frame;  
  4.     _frame.origin.x = -100;  
  5.     self.frame = _frame;  
  6.   
  7.     [UIView beginAnimations:nil context:nil];  
  8.     [UIView setAnimationDuration:0.15];  
  9.     _frame.origin.x = x+100;  
  10.     self.frame = _frame;  
  11.     self.alpha = 0;  
  12.     [UIView commitModalAnimations];  
  13.   
  14.       
  15.     [UIView beginAnimations:nil context:nil];  
  16.     [UIView setAnimationDuration:0.15];  
  17.     _frame.origin.x = x;  
  18.     self.frame = _frame;  
  19.     self.alpha = 1;  
  20.     [UIView commitModalAnimations];   
  21. }  

posted on 2012-03-27 09:05  pengyingh  阅读(587)  评论(0)    收藏  举报

导航