Multiple Simultaneous UIViewAnimations on a Single UIView

孤街醉人 提交于 2019-12-04 10:25:30
eckyzero

The answer is not to use UIViewAnimation blocks but instead CABasicAnimations. With them you can manipulate the center coordinate (x,y) separately. Here's what my code looks like now:

    UIView *view = views[i];

    // Add the horizontal animation
    CABasicAnimation *horizontal = [CABasicAnimation animationWithKeyPath:@"position.x"];

    horizontal.delegate = self;
    horizontal.fromValue = [NSNumber numberWithFloat:25.0];
    horizontal.toValue = [NSNumber numberWithFloat:50.0];
    horizontal.repeatCount = INFINITY;
    horizontal.duration = 6;
    horizontal.autoreverses = YES;
    horizontal.beginTime = 0; // ignore delay time for now
    horizontal.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    [view.layer addAnimation:horizontal forKey:@"horizontal_animation"];

    // Add the vertical animation
    CABasicAnimation *vertical = [CABasicAnimation animationWithKeyPath:@"position.y"];

    vertical.delegate = self;
    vertical.fromValue = [NSNumber numberWithFloat:100.0];
    vertical.toValue = [NSNumber numberWithFloat:400.0];
    vertical.repeatCount = INFINITY;
    vertical.duration = 2;
    vertical.autoreverses = YES;
    vertical.beginTime = 0; // ignore delay time for now
    vertical.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    [view.layer addAnimation:vertical forKey:@"vertical_animation"];

This allows me to handle repeat, duration, etc. in two separate animations. Then, when my animations are over, I can just call the follow method to remove animations. Either,

    [view.layer removeAllAnimations];

or, if I want a more specific animation removed,

    [view.layer removeAnimationForKey:@"vertical_animation"];

Then, if you want to some more custom control over when the animation starts/stops, you just need to add the delegate methods like so:

    -(void)animationDidStart:(CAAnimation *)anim {
        // custom code here
    }

    -(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
        // custom code here
    }

It's pretty sweet and easy. Hope this helps anyone in a similar need. Cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!