我正在尝试使用 animateWithDuration: 方法在 iOS 中制作动画。
我正在屏幕上移动图像(UIImageView 中的云的简单图片),然后让该动画循环运行,我想在每次穿过屏幕时更改速度(持续时间)。
我已经尝试了几种方法,但对我来说两种方法都不正确。
虽然我首先可以像这样使用 UIViewAnimationOptionRepeat:
[UIImageView animateWithDuration:arc4random() % 10 + 1
delay:0.0
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionRepeat
animations:^{
//moving the cloud across the screen here
}
completion:^(BOOL finished) {
NSLog(@"Done!");
}];
但这似乎并没有再次调用 arc4random() 来重置持续时间……即云只会在每次应用启动时以随机速度穿过屏幕,而不是每次动画循环时。
然后我尝试使用完成 block 再次触发动画,如下所示:
-(void)animateMethod
{
[UIImageView animateWithDuration:arc4random() % 10 + 1
delay:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
//moving the cloud across the screen here
}
completion:^(BOOL finished) {
NSLog(@"Done!");
[self animateMethod];
}];
}
这给了我正在寻找的效果,但是当我使用导航 Controller 推送到另一个 View 时,完成 block 似乎在无休止的循环中被触发(我的日志被“完成!”垃圾邮件)
有人知道如何获得我想要的正确方法吗?
最佳答案
您走在正确的轨道上。关键是你只需要在动画完成时循环,而不是在失败时循环。所以你需要在告诉它循环之前检查 finished
BOOL
是否为真。
-(void)animateMethod
{
[UIImageView animateWithDuration:arc4random() % 10 + 1
delay:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
//moving the cloud across the screen here
}
completion:^(BOOL finished) {
if (finished) {
NSLog(@"Done!");
[self animateMethod];
}
}];
}
这种方法非常适用于像这样非常简单的动画,以及当您只制作少量动画时,例如一次制作 3-5 朵云。除此之外,您可能希望使用 NSTimer 或 CADisplayLink 设置自己的动画循环并调整其中的云帧。这是一种更加手动的方式,但即使在 UIKit 中,它也会为您提供一些漂亮的动画。
关于iphone - 为循环 UIView 动画 block 添加随机性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508102/