嵌套未知数量的UIView动画

时间:2013-01-10 22:54:43

标签: iphone ios cocoa

我正在构建一个iPhone卡片游戏,我希望在每轮结束时为桌面上的玩家卡片制作动画。玩家可以在每轮结束时拥有任意数量的牌,因此我无法以任何静态方式嵌套动画代码。如果我有以下代码来动画表格中的两个卡片视图对象...

UICardView * __block card1 = [[UICardView alloc] init];
UICardView * __block card2 = [[UICardView alloc] init];
[UIView animateWithDuration:1.0f 
                      delay:0.0f 
                    options:UIViewAnimationCurveLinear 
                 animations:^{
                                card1.frame = CGRectOffset(cardView.frame, 0.0f, -300.0f);
                             } 
                 completion:^(BOOL finished) {
                                [UIView animateWithDuration:1.0f
                                                      delay:0.0f 
                                                    options:UIViewAnimationCurveLinear 
                                                 animations:^{
                                                                 card2.frame = CGRectOffset(cardView.frame, 0.0f, -300.0f);
                                                             } 
                                                 completion:nil]
                 }];

...如何构建我的代码以动画NSOrderedList中未知数量的卡片视图对象?

非常感谢你的智慧!

2 个答案:

答案 0 :(得分:1)

-(void)animateCards:(NSMutableArray *)cards
{
    if(cards.count) {
        UICardView *cardView = [cards lastObject];
        [UIView animateWithDuration:1.0f 
                              delay:0.0f 
                            options:UIViewAnimationCurveLinear 
                         animations:^{
                             cardView.frame = CGRectOffset(cardView.frame, 0.0f, -300.0f);
                         } 
                         completion:^(BOOL finished) {
                             [cards removeLastObject];
                             [self animateCards:cards];
                         }
    } else {
        NSLog("Finished animating cards!");
    }
}

您可以使用UICardView数组调用animateCards。 (确保复制,因为数组最后会为空)

例如,如果您将self.playerCards作为UICardView数组,您想要设置动画,只需这样调用

NSMutableArray *cardsToBeAnimated = [NSMutableArray arrayWithArray:self.playerCards];
[self animateCards:cardsToBeAnimated];

答案 1 :(得分:0)

...或递归,或许:

- (void)animateCardNTimes:(int)times
{
    if (times <= 0) return;

    __block CardView *cv = [[CardView alloc] init]; 
    [UIView animateWithDuration:1.0f 
                          delay:0.0f 
                         options:UIViewAnimationCurveLinear 
                      animations:^{
                          cv.frame = CGRectOffset(cardView.frame, 0.0f, -300.0f);
                      } 
                      completion:^(BOOL finished) {
                          [self animateCardNTimes:times - 1];
                      }
    ];
}