同时为多个UIView设置动画

时间:2015-07-24 20:06:47

标签: ios objective-c animation uiview

我有一堆(9个左右)UIButton我想同时制作动画。我基本上希望他们都能在淡入淡出,但在不同的时间点。因此viewOne.alpha将在时间t + .1淡入,viewTwo将在时间t + .15淡入,viewThree将在t + .17等时淡入。

它们也应该以随机的速度消失。

我认为我可以用CABasicAnimation完成此操作?我的问题基本上是我可以同时制作多个动画,因为我似乎不能同时使用多个UIViewAnimation块。

2 个答案:

答案 0 :(得分:3)

您无法使用一个UIView动画块执行此操作,但您可以使用'performSelector:withObject:afterDelay:`设置动画块。例如:

[self performSelector:@selector(fadeIn:) withObject:button1 afterDelay:0.1f];
[self performSelector:@selector(fadeIn:) withObject:button2 afterDelay:0.15f];

- (void)fadeIn:(UIView *)view {
    // start animation with random speed
}

答案 1 :(得分:1)

您可以使用 + animateKeyframesWithDuration:delay:options:animations:completion:方法。 E.g。

#import "ViewController.h"

static NSTimeInterval const kButtonsAnimationDuration = 1.0;
static NSTimeInterval const kButtonsAnimationDelay = 0.0;

#define ARC4RANDOM_MAX 0x100000000

@interface ViewController ()

@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *buttons;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self animateButtons];
}

- (void)animateButtons {
    double startTimes[] = {0.1, 0.15, 0.17, 0.22, 0.24}; // must be equal to the number of buttons in the array self.buttons
    double *startTimesPtr = startTimes;
    [UIView animateKeyframesWithDuration:kButtonsAnimationDuration delay:kButtonsAnimationDelay options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
        for (NSUInteger i = 0u; i < self.buttons.count; ++i) {
            double startTime = startTimesPtr[i];
            UIButton *button = self.buttons[i];
            [self addKeyframeWithButton:button startTime:startTime];
        }
    } completion:nil];
}

- (void)addKeyframeWithButton:(UIButton *)button startTime:(double)startTime {
    double correctedStartTime = startTime / kButtonsAnimationDuration;
    double randomDuration = ((double)arc4random() / ARC4RANDOM_MAX);

    button.alpha = 0.0;
    [UIView addKeyframeWithRelativeStartTime:correctedStartTime relativeDuration:randomDuration animations:^{
        button.alpha = 1.0;
    }];
}

@end