gpt4 book ai didi

ios - 单个 UIView 上的多个同时 UIViewAnimations

转载 作者:可可西里 更新时间:2023-11-01 05:35:40 48 4
gpt4 key购买 nike

目标:
在单个 UIView 上同时播放多个动画。
问题:
据我所知,这是不可能的。每个动画必须按顺序出现,不能重叠。

本质上,我希望单个 UIView 在垂直方向上设置动画,同时在水平方向上设置动画。因为我使用的是 UIViewAnimationOptionRepeat,所以我不能在 onCompletion 中嵌套任何其他动画:这是我想要工作但没有的:

[UIView animateWithDuration:duration
delay:kANIMATION_DELAY
options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{

object.frame = CGRectMake(object.frame.origin.x + 40,
object.frame.origin.y,
object.frame.size.width,
object.frame.size.height);

[UIView animateWithDuration:duration
delay:kANIMATION_DELAY
options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{

object.frame = CGRectMake(object.frame.origin.x,
object.frame.origin.y - 40,
object.frame.size.width,
object.frame.size.height);

} completion:^(BOOL finished) {
}];

} completion:^(BOOL finished) {
}];

最佳答案

答案不是使用 UIViewAnimation block ,而是使用 CABasicAnimations。使用它们,您可以单独操作中心坐标 (x,y)。这是我的代码现在的样子:

    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"];

这允许我在两个单独的动画中处理重复、持续时间等。然后,当我的动画结束时,我可以调用 follow 方法来删​​除动画。要么,

    [view.layer removeAllAnimations];

或者,如果我想删除更具体的动画,

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

然后,如果你想对动画开始/停止的时间进行更多的自定义控制,你只需要像这样添加委托(delegate)方法:

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

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

它非常甜蜜和简单。希望这可以帮助任何有类似需求的人。干杯!

关于ios - 单个 UIView 上的多个同时 UIViewAnimations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21036434/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com