0

在我的 ipad 应用程序中,我有 200 张图像,我将这些图像添加到一个数组中。
然后通过循环将此数组添加到图像视图中。然后,我将此图像视图添加为滚动视图的子视图。

当我打开应用程序时,我的应用程序崩溃了。
我尝试减小图像大小。但是,它没有用。

我的一个朋友首先告诉我应该只添加 image1 和 image2。
当用户滚动 image1 时,它会显示 image2。
之后 image1 从图像视图中删除。
并将 image3 添加到图像视图。

他告诉它可以保持内存使用。
但是,我不知道我该怎么做?:D
请给我一些例子。
提前致谢。

我的代码在这里,

- (void)viewDidLoad
{
[super loadView];
self.view.backgroundColor = [UIColor grayColor];

UIScrollView *ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height)];
ScrollView.pagingEnabled = YES;

// Create a UIImage to hold Info.png
UIImage *image1 = [UIImage imageNamed:@"Image-001.jpg"];
UIImage *image2 = [UIImage imageNamed:@"Image-002.jpg"];
UIImage *image200 = [UIImage imageNamed:@"Image-200.jpg"];

NSArray *images = [[NSArray alloc] initWithObjects:image1,image2,...,image200,nil];

NSInteger numberOfViews = 200;
for (int i = 0; i < numberOfViews; i++) 
{
CGFloat xOrigin = i * self.view.frame.size.width;

UIImageView *ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height-44)];
[ImageView setImage:[images objectAtIndex:i]];

[ScrollView addSubview:ImageView];
}
ScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:ScrollView];
4

2 回答 2

0

看起来您正在访问索引为 0..200 的图像数组,但它只包含三个元素。设置numberOfViews = 3;或索引到数组中,如下所示:

ImageView.image = images[i%3];

模索引将导致您以重复顺序添加三个图像中的每一个,并且仍然允许您使用更多的滚动视图子视图进行测试。我怀疑你的崩溃与只有 200 张图像的内存有关,除非它们是超大的。

于 2013-02-10T17:28:21.083 回答
0

您应该使用表格视图来显示图像。您不想创建所有这些图像的数组,因为这会将所有这些图像放入内存 - 这不是一件好事。您甚至不需要创建一个数组来保存名称,因为它们具有您可以从整数轻松构造的名称(您可以从 tableView:cellForRowAtIndexPath: 方法中的 indexPath.row 获得)。像这样的东西:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 200;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString *imageName = [NSString stringWithFormat:@"Image-%.3d.jpg",indexPath.row +1];
    UIImage *image = [UIImage imageNamed:imageName];
    cell.imageView.image = image;
    return cell;
}

这个例子只是使用单元格的默认 imageView 来显示图像,它非常小。您可能希望创建一个自定义单元格,其中包含更大的图像视图(如果您希望每行有多个图像,则可以并排创建几个)。

于 2013-02-10T18:04:38.197 回答