简体   繁体   中英

Getting two images to appear in random sequence iOS

I am new to the community, so let me know if my question is unclear. I am trying to make a choice reaction exercise on the iPAD. There are two images that should appear in random sequence on the left and right of the screen, and the user will respond by tapping a button that corresponds to the position of the appeared image. Here's the problem, I tried to get the two images to appear at random order using the following way:

- (void) viewDidAppear:(BOOL)animated
{
   for(int n = 1; n <= 20; n = n + 1)
   {
      int r = arc4random() % 2;
      NSLog(@"%i", r);
      if(r==1)
      {
        [self greenCircleAppear:nil finished:nil context: nil];
      }
      else
     {
        [self redCircleAppear:nil finished:nil context: nil];
     }
  }
}

However, 20 random numbers get generated while only 1 set of animation is run. Is there a way to let the animation finish running in each loop before the next loop begins? Any help is appreciated, thanks in advance!

When you say "only one set of animation is run" I'm assuming that means greenCircleAppear and redCircleAppear begin the sequence of images appearing and the user pressing a button. If that's the case, I'd recommend not using a for loop in viewDidAppear but instead have viewDidAppear initialize the current state and call a method that presents the next animation. When the animation is finished, have it call the method that presents the next animation. Something along these lines:

Add this to the interface:

@interface ViewController ()

@property NSInteger currentIteration;

@end

This is in the implementation:

- (void)viewDidAppear:(BOOL)animated {
    self.currentIteration = 0;
    [self showNextAnimation];
}

- (void)greenCircleAppear:(id)arg1 finished:(id)arg2 context:(id)arg3 {
    //perform animation
    NSLog(@"green");
    [self showNextAnimation];
}

- (void)redCircleAppear:(id)arg1 finished:(id)arg2 context:(id)arg3 {
    //perform animation
    NSLog(@"red");
    [self showNextAnimation];
}

- (void)showNextAnimation {
    self.currentIteration = self.currentIteration + 1;
    if (self.currentIteration <= 20) { //you should replace '20' with a constant
        int r = arc4random() % 2;
        NSLog(@"%i", r);
        if(r==1)
        {
            [self greenCircleAppear:nil finished:nil context: nil];
        }
        else
        {
            [self redCircleAppear:nil finished:nil context: nil];
        }
    }
    else {
        //do what needs to be done after the last animation
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM