2014-12-20 28 views
2

所以这就是我的iOS程序。按下开始按钮后,企鹅的随机图像将从右侧出现,向左移动并消失,并重复一遍又一遍,而无需再次按下开始按钮。我试图让每一个周期都出现一组不同的企鹅。它确实循环但是,每个循环都会显示相同的企鹅。当我按下开始按钮时,它只变成一只不同的企鹅,但我想按一下按钮,当循环继续时,每条循环都会出现不同的企鹅。我把随机码放在循环中,但是我没有看到它随机化了每一个循环,每次按下开始按钮时它都会随机化。任何想法如何解决它?iOS:随机在每个循环中都不起作用

-(IBAction)start:(id)sender { 
[UIView animateKeyframesWithDuration:3 delay:0 options:UIViewKeyframeAnimationOptionRepeat animations:^{ 
    [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.3 animations:^{ 
    NSArray *imageNameArray = [[NSMutableArray alloc] initWithObjects:@"Right.png", @"Left.png", @"Straight.png", nil]; 
    Penguin.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])]]; 
    Penguin.center = CGPointMake(294, 373); 
    Penguin.alpha = 1; 
    Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}]; 
    [UIView addKeyframeWithRelativeStartTime:0.3 relativeDuration:0.4 animations:^{ 
    Penguin.center = CGPointMake(Penguin.center.x - 200, Penguin.center.y);}]; 
    [UIView addKeyframeWithRelativeStartTime:0.7 relativeDuration:0.3 animations:^{ 
    Penguin.alpha = 0; 
    Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}]; 
    }completion:nil 
    ]; 
    } 

回答

0

我认为重复动画的所有参数只设置一次,所以随机图像只被选中一次。代替制作重复动画,请从动画的完成块调用start:方法,并在动画方法外执行随机选取,

-(IBAction)start:(id)sender { 

    NSArray *imageNameArray = [[NSMutableArray alloc] initWithObjects:@"Right.png", @"Left.png", @"Straight.png", nil]; // There's no need to define this every time the method is called. It would be better to make this a property, and define it outside this method 
    Penguin.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])]]; 

    [UIView animateKeyframesWithDuration:3 delay:0 options:0 animations:^{ 
     [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.3 animations:^{ 

      Penguin.center = CGPointMake(294, 373); 
      Penguin.alpha = 1; 
      Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}]; 
     [UIView addKeyframeWithRelativeStartTime:0.3 relativeDuration:0.4 animations:^{ 
      Penguin.center = CGPointMake(Penguin.center.x - 200, Penguin.center.y);}]; 
     [UIView addKeyframeWithRelativeStartTime:0.7 relativeDuration:0.3 animations:^{ 
      Penguin.alpha = 0; 
      Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}]; 
    }completion:^(BOOL finished) { 
     [self start:nil]; 
    } 
    ]; 
} 
+0

thanks mate!它像我想要的那样完美运行! –