Trying to perform multiple animations at once

2019-09-07 20:38发布

问题:

Seems strange that i could not find any answer for this all over the net, but seems that if you want to move 6 UIViews at the same time in a different speed ,you can't do that.

If i am using one of this 2 example, i get that sometimes only some of the views are moving, and sometimes all of them (as expected) .

There is no way to move 6-7-8 UIViews at the same time ,with different duration?

1.

for(UIButton *button in buttons)
{

    float r=   arc4random()%10;
    float t =0.1+ 1.0/r;
[UIView beginAnimations:@"Anim0" context:nil];
[UIView setAnimationDuration:t];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:button cache:YES];

CGRect newframe=button.frame;
newframe.origin.y=0;
button.frame=newframe;

[UIView commitAnimations];

}

2.

 for(UIButton *button in buttons)
    {
         int random=arc4random()%10;
        float time=0.5+ 1/(float)random;
        CGRect newframe=button.frame;
        newframe.origin.y=0;
        [UIView transitionWithView:button
                          duration:time
                           options:UIViewAnimationOptionCurveEaseInOut
                        animations:^{
                           button.frame=newframe;
                        }
                        completion:nil];
    }

回答1:

You need to limit the random number generator.

Your function...

arc4random() % 10;

Will sometimes return 0.

Then passing this into...

float time = 0.5 + 1/random;

Will make time = inf.

You can see this by logging out the time values.

A time of inf will make the button not animate.



回答2:

Of course it is possible. The problem is that you're sending the wrong message. Based on your second snippet, this is an example of how it could be done:

for (UIButton *button in self.buttons) {

    int random        = (arc4random() % 10) + 1; // "+1" Added later in the answer, see Fogmeister's answer
    float time        = 0.5 + 1 / (float)random; 
    CGRect newframe   = button.frame;
    newframe.origin.y = 0;

    [UIView animateWithDuration:time
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         button.frame = newframe;
                     } completion:^(BOOL finished) {
                         // The animation have finished
                     }];
}