2012-03-22 35 views
1

我能夠從數組中顯示8個圖像中的5個圖像。但我得到這個代碼重複的圖像:如何顯示圖像,而無需在objective-c中重複數組?

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]; 
+0

檢查中問題的功能:HTTP:// stackoverflow.com/questions/9798647/objective-c-uibutton-image-with-nsarray-in-a-random-order – Sarah 2012-03-22 06:54:40

回答

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

相關問題