在我的FirstViewcontroller
我有一个包含1
到25
值的选择器,如果用户在下一个屏幕上的选择器中选择5,它应该从25个图像中随机显示5个图像重复那5张图片。如果用户选择另一个数字意味着它将该数字作为输入,它应该根据该数字显示图像。如果我运行我的代码意味着每次显示所有25个图像未选择数字图像。这是我的代码
- (void)viewDidLoad {
myImageNames = [[NSMutableArray alloc] init];
[myImageNames addObject:[UIImage imageNamed:@"Red.png"]];
[myImageNames addObject:[UIImage imageNamed:@"Blue.png"]];
[myImageNames addObject:[UIImage imageNamed:@"LightRed.png"]];
[myImageNames addObject:[UIImage imageNamed:@"Orange.png"]];
.
.
.
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ChangingImgView:) userInfo:nil repeats:YES];
}
- (void) ChangingImgView:(int)selectedNumberFromPicker {
selectedNumberFromPicker = [num intValue];
for (int i=0; i < selectedNumberFromPicker; i++) {
index = arc4random() % 25;
NSString *strIndex = [NSString stringWithFormat:@"%i",index];
[myImageNames addObject:strIndex];
imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
imgBtn.frame = CGRectMake(250, 300, 170, 220);
UIImage *img = [myImageNames objectAtIndex:index];
[imgBtn setBackgroundImage:img forState:UIControlStateNormal];
[imgBtn addTarget:self action:@selector(ClickingOnImage) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imgBtn];
}
}
请帮帮我。
答案 0 :(得分:1)
您也可以使用NSSet而不是使用NSMutableArray
doc apple
You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.
答案 1 :(得分:0)
首先suffle
myImageNames
images
display
使用this链接。
现在images
来自myImageNames
的前{5} {{1}}。
答案 2 :(得分:0)
int count = 5;
NSMutableArray *inputImages = [myImageNames mutableCopy];
NSMutableArray *randomImages;
for (int i = 0; i<count; i++) {
int index = arc4random_uniform([inputImages count]);
[randomImages addObject:[inputImages objectAtIndex:index]];
[inputImages removeObjectAtIndex:index];
}
答案 3 :(得分:0)
尝试使用此for循环来获取随机索引的特定数量的图像。使用selectedImgArray显示所选图像。 myImageNames是你的原始数组。
NSInteger index;
NSMutableArray *selectedImgArray = [[NSMutableArray alloc] init];
for (int i=0; i < selectedNumberFromPicker; i++) {
index = arc4random() % 25;
UIImage *selImg = (UIImage *)[myImageNames objectAtIndex:index];
if ([selectedImgArray containsObject:selImg]) {
i--;
continue;
}
[selectedImgArray addObject:selImg];
}