简体   繁体   中英

showing four random images

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

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];
}

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]];
    }
}

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