如何随机化页面滚动视图中的图像
Posted
技术标签:
【中文标题】如何随机化页面滚动视图中的图像【英文标题】:How to randomize images in a page scrollview 【发布时间】:2011-08-05 08:35:18 【问题描述】:我有 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 张图像,但每次我运行应用程序时,应用程序都会从随机图像开始,但我仍然可以滚动浏览图像。我希望你们能理解我的问题。
【问题讨论】:
【参考方案1】:您可以在每次创建 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
。
【讨论】:
啊,这很好...谢谢...但是当我尝试代码时,它说 shuffle 不响应 NSMutableArray。 警告应该没问题。无论如何,请参阅我的编辑以了解如何删除它。 你在这方面有什么成功吗? 我已经这样做了,我现在正在准备一些图像...很快就会更新这个问题:) 抱歉,上周末忙于一些网络内容以上是关于如何随机化页面滚动视图中的图像的主要内容,如果未能解决你的问题,请参考以下文章