1

在我的选择器中FirstViewcontroller包含值,如果用户在下一个屏幕的选择器中选择 5,它应该从 25 个图像中随机显示 5 个图像,而不重复这 5 个图像。如果用户选择另一个数字意味着它将该数字作为输入,它应该根据该数字显示图像。如果我运行我的代码意味着每次它显示所有 25 张图像而不是选定的数字图像。这是我的代码125

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

请帮我。

4

4 回答 4

1

你也可以使用 NSSet 而不是使用 NSMutableArray

苹果医生

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.

于 2012-12-20T08:27:12.297 回答
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];

}
于 2012-12-20T13:34:17.720 回答
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];
}
于 2012-12-20T13:11:14.930 回答
0

首先,suffle您使用链接。myImageNamesimages

现在display前 5 个images来自myImageNames.

于 2012-12-20T08:22:41.410 回答