2014-12-20 46 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!它像我想要的那樣完美運行! –