我有两张图片," image1"和" image2" 。我想要做的是每当我打开iOS模拟器时,它会随机加载其中一个图像。有没有办法做到这一点?
答案 0 :(得分:1)
在ViewDidLoad
或您想要的imageView
所在的任何地方:
//create image array
NSArray *imagesArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"image1.png"], [UIImage imageNamed:@"image2.png"], nil];
//random number
int r = arc4random() % [imagesArray count];
//create imageview
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[imageView setImage:[imagesArray objectAtIndex:r]];
[self.view addSubview:imageView];
答案 1 :(得分:1)
#include <stdlib.h>
@interface YourViewController()
//Add an Image View to the storyboard on your view controller, then add outlet to your code for that image view
@property (weak, nonatomic) IBOutlet UIImageView *anImageView;
@end
@implementation YourViewController
- (void)viewDidLoad
{
//random number 0 or 1
int r = arc4random() % 2;
UIImage *image1 = [UIImage imageNamed:@"image1"];
UIImage *image2 = [UIImage imageNamed:@"image2"];
if (r == 0){
//if random number is 0, set image view to image1 when view loads
[self.anImageView setImage:image1];
}
else{
//if random number is 1, set image view to image2 when view loads
[self.anImageView setImage:image2];
}
}
@end