2014-12-20 2 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

감사 메이트! 내가 원하는 것처럼 완벽하게 작동했습니다! –

관련 문제