ArnoHlaMoe
ArnoHlaMoe

Reputation: 287

Press button and go to random view in iOS App

I have 32 different views in my iPhone app, and when the user presses a button, I need the view to change to either of the 32 views randomly. How do you do that?

Upvotes: 0

Views: 141

Answers (1)

shannoga
shannoga

Reputation: 19869

First Set an array with all the views in it.

NSArray *viewsArray = [NSArray arrayWithObjects:view1,view2....,nil];

Second when the user taps the button get one of the views with:

- (UIView*) getRandomView {
  int rand = arc4random_uniform([viewsArray count]);
  UIView *selectedView = [viewsArray objectAtIndex:rand];
  return selectedView;
}

Lastly add the returned view as a subview:

-(void)userTappedTheButton{
   [self.view addSubView:[self getRandomView]];
}

Upvotes: 2

Related Questions