Reputation: 1
I am using this code to generate random image to UIImageView. When I click the button, it apears another image. I would like to ask you how to create four imageviews - click button -> apears four different random images.
ViewController.h
@interface ViewController : UIViewController {
IBOutlet UIImageView *imageView;
// IBOutlet UIImageView *imageView2;
}
-(IBAction) randomImage;
ViewController.m
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", nil];
int count = [images count]
int index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
// imageView2.image = ....
}
I created four imageViews in storyboard and I was trying something like above // imageView2.image... but it it not the right solution :-) Thank you for your help
Upvotes: 0
Views: 96
Reputation: 5148
Code to list 4 random image:
NSMutableArray *images = [[NSMutableArray alloc] initWithArray: @[@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg"]];
int countImg = images.count;
for (int i = 0; i < countImg; i++) {
NSInteger index = arc4random() % images.count;
NSLog(@"Image%d name = %@",i , [images objectAtIndex:index]);
[images removeObjectAtIndex:index];
}
Upvotes: 3
Reputation: 119031
Rather than using IBOutlet UIImageView *imageView;
, use IBOutletCollection(UIImageView) NSArray *imageViews;
and connect all of your image views to this.
Then, in your code:
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", nil];
NSInteger count = [images count];
for (UIImageView *imageView in self.imageViews) {
NSInteger index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
}
}
Upvotes: 0