如何在objective-c中不重复显示图像?

时间:2012-03-22 06:50:15

标签: iphone uiimage nsarray

我能够从阵列中显示8个图像中的5个图像。但我正在使用此代码重复图像:

int index1 = arc4random()%8;
UIImage *card1=[UIImage imageNamed:[imageArray objectAtIndex:index1]];
[b1 setImage:card1 forState:UIControlStateNormal];

int index2 = arc4random()%8;
UIImage *card2=[UIImage imageNamed:[imageArray objectAtIndex:index2]];
[b2 setImage:card2 forState:UIControlStateNormal];

int index3 = arc4random()%8;
UIImage *card3=[UIImage imageNamed:[imageArray objectAtIndex:index3]];
[b3 setImage:card3 forState:UIControlStateNormal];

int index4 = arc4random()%8;
UIImage *card4=[UIImage imageNamed:[imageArray objectAtIndex:index4]];
[b4 setImage:card4 forState:UIControlStateNormal];

int index5 = arc4random()%8;
UIImage *card5=[UIImage imageNamed:[imageArray objectAtIndex:index5]];
[b5 setImage:card5 forState:UIControlStateNormal];

1 个答案:

答案 0 :(得分:0)

使用原始数组创建一个NSMutableArray,然后将其洗牌。 为了改组,您可以使用以下代码:

//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end


//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{

  static BOOL seeded = NO;
  if(!seeded)
  {
    seeded = YES;
    srandom(time(NULL));
  }

    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end

你可以像这样使用改组:

NSMutableArray* array = [NSMutableArray arrayWithArray:imageArray];
[array shuffle];
[array objectAtIndex:0];
[array objectAtIndex:1];
[array objectAtIndex:2];
[array objectAtIndex:3];
[array objectAtIndex:4];
...

改组代码来自此question