我有12张图片,存储在一个数组......
我用它来输出图像。
scrollView = [[UIScrollView alloc] init];
CGRect scrollFrame;
scrollFrame.origin.x = 0;
scrollFrame.origin.y = 0;
scrollFrame.size.width = WIDTH_OF_SCROLL_PAGE;
scrollFrame.size.height = HEIGHT_OF_SCROLL_PAGE;
scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
scrollView.bounces = YES;
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.userInteractionEnabled = YES;
NSMutableArray *slideImages = [[NSMutableArray alloc] init];
[slideImages addObject:@"KODAK1.png"];
[slideImages addObject:@"KODAK2.png"];
[slideImages addObject:@"KODAK3.png"];
[slideImages addObject:@"KODAK4.png"];
[slideImages addObject:@"KODAK5.png"];
[slideImages addObject:@"KODAK6.png"];
[slideImages addObject:@"KODAK7.png"];
[slideImages addObject:@"KODAK8.png"];
[slideImages addObject:@"KODAK9.png"];
[slideImages addObject:@"KODAK10.png"];
[slideImages addObject:@"KODAK11.png"];
[slideImages addObject:@"KODAK12.png"];
srandom(time(NULL));
int x = arc4random() % 12;
for ( int i = 0 ;i<[slideImages count]; i++) {
//loop this bit
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[slideImages objectAtIndex:i]]];
imageView.frame = CGRectMake((WIDTH_OF_IMAGE * i) + LEFT_EDGE_OFSET, 0 , WIDTH_OF_IMAGE, HEIGHT_OF_IMAGE);
[scrollView addSubview:imageView];
[imageView release];
}
[scrollView setContentSize:CGSizeMake(WIDTH_OF_SCROLL_PAGE * ([slideImages count] +0), HEIGHT_OF_IMAGE)];
[scrollView setContentOffset:CGPointMake(0, 0)];
[self.view addSubview:scrollView];
[self.scrollView scrollRectToVisible:CGRectMake(WIDTH_OF_IMAGE,0,WIDTH_OF_IMAGE,HEIGHT_OF_IMAGE) animated:YES];
[super viewDidLoad]
如何在UIView中输出随机图像?因为有12个图像,但每次我运行应用程序时,应用程序将以随机图像开始,但我仍然可以滚动图像。我希望你们能理解我的问题。
答案 0 :(得分:3)
每次创建NSMutableArray时都可以“洗牌”:
NSMutableArray *slideImages = [[NSMutableArray alloc] init];
...
[slideImages shuffle];
...
因此,每次使用不同的顺序初始化UIScrollView时。
shuffle
不是SDK的一部分。有关示例实施,请have a look to this:
@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
导入包含类别声明的头文件:
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
您想要使用shuffle
的任何地方。