我正在使用此代码为UIImageView生成随机图像。单击按钮时,它会显示另一个图像。我想问你如何创建四个图像视图 - 单击按钮 - > apears四个不同的随机图像。
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 = ....
}
我在故事板中创建了四个imageViews,我尝试了类似上面的内容// imageView2.image ...但它不是正确的解决方案:-) 谢谢你的帮助
答案 0 :(得分:3)
列出4个随机图像的代码:
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];
}
答案 1 :(得分:0)
使用IBOutlet UIImageView *imageView;
而不是使用IBOutletCollection(UIImageView) NSArray *imageViews;
,并将所有图片视图连接到此。
然后,在您的代码中:
- (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]];
}
}