CAAnimationDelegate从名字就可以看出这是一个动画的代理,里面有什么方法呢?其中最主要的就是一个动画结束之后的代理方法:-animationDidStop:finished:,这个方法在动画结束之后用来更新图层,CAAnimationDelegate在任何头文件中都找不到,但是可以在CAAnimation的头文件中找到相关函数。
来说下它的使用方法,举个简单例子,以前面博客中改变图层颜色为例,点击按钮改变图层颜色:
- (IBAction)changeColor { //create a new random color CGFloat red = arc4random() / (CGFloat)INT_MAX; CGFloat green = arc4random() / (CGFloat)INT_MAX; CGFloat blue = arc4random() / (CGFloat)INT_MAX; UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0]; //create a basic animation CABasicAnimation *animation = [CABasicAnimation animation]; animation.keyPath = @"backgroundColor"; animation.toValue = (__bridge id)color.CGColor; animation.delegate = self; //apply animation to layer [self.colorLayer addAnimation:animation forKey:nil]; } - (void)animationDidStop:(CABasicAnimation *)anim finished:(BOOL)flag { //set the backgroundColor property to match animation toValue [CATransaction begin]; //设置动画变化过程是否显示,默认YES,不显示 [CATransaction setDisableActions:YES]; self.colorLayer.backgroundColor = (__bridge CGColorRef)anim.toValue; [CATransaction commit]; }
如果有多个动画,怎么来判断哪个是哪个呢?好在CAAnimation实现了KVC,可以通过设置的键值的方法来拿到不同的动画:
CABasicAnimation *animation = [CABasicAnimation animation]; animation.keyPath = @"transform"; animation.toValue = [NSValue valueWithCATransform3D:transform]; animation.duration = 0.5; animation.delegate = self; //设置键值,可随意设置 [animation setValue:handView forKey:@"handView"]; [handView.layer addAnimation:animation forKey:nil]; //获取到执行了该动画的对象view UIView *handView = [anim valueForKey:@"handView"];