#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIView *redView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { CABasicAnimation *anim = [CABasicAnimation animation]; anim.keyPath = @"position.y"; anim.toValue = @400; /** * 1:CABasicAnimation:主要用于缩放,平移,转场CATransiton动画主要用于场景切换,CAKeyFrameAnimation:关键帧动画,主要用于图标抖动等 2:在CABasicAnimation中,设置anim.removedOnCompletion,目的是动画结束后不删除动画,anim.fillMode = kCAFillModeForwards;设置动画的模式,设置这两个属性,可以不让动画执行结束后,恢复到原来的位置,而是保留结束动画的状态 3:CAAnimationGroup:她会自动执行数组animations里的动画 */ // anim.removedOnCompletion = NO; // anim.fillMode = kCAFillModeForwards; // // [self.redView.layer addAnimation:anim forKey:nil]; CABasicAnimation *anim2 = [CABasicAnimation animation]; anim2.keyPath = @"transform.scale"; anim2.toValue = @0.5; // anim2.removedOnCompletion = NO; // anim2.fillMode = kCAFillModeForwards; // [self.redView.layer addAnimation:anim2 forKey:nil]; CAAnimationGroup *group = [CAAnimationGroup animation]; //会自动执行animations数组当中所有的动画对象 group.animations = @[anim,anim2]; group.removedOnCompletion = NO; group.fillMode = kCAFillModeForwards; [self.redView.layer addAnimation:group forKey:nil]; } @end
可以同时执行多个动画.
创建组动画
CAAnimationGroup *group = [CAAnimationGroup animation];
平移
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"position.y";
anim.toValue = @400;
缩放
CABasicAnimation *scaleAnim = [CABasicAnimation animation];
scaleAnim.keyPath = @"transform.scale";
scaleAnim.toValue = @0.5;
设置动画组属性
group.animations = @[anim,scaleAnim];
group.removedOnCompletion = NO;
group.fillMode = kCAFillModeForwards;
添加组动画
[self.redView.layer addAnimation:group forKey:nil];
使用动画组的好处,不需要每次都去添加动画,设置动画完成时的属性.
只需要把要执行的动画,添加到动画组的animations数组当中即可,
最后把组动画添加到层上面,就会自动执行数组当中的动画.
动画完成时设置的属性也只需要设置一次.
时间: 2024-10-06 06:29:36