添加新图像并从图像视图中删除旧图像

时间:2013-02-10 17:24:35

标签: ios xcode ipad cocoa-touch

在我的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];

2 个答案:

答案 0 :(得分:0)

看起来你正在索引0..200访问images数组,但它只包含三个元素。设置numberOfViews = 3;,或者像这样索引到数组中:

ImageView.image = images[i%3];

模数索引将使您以重复序列添加三个图像中的每一个,并且仍然允许您使用更多数量的scrollView子视图进行测试。我怀疑你的崩溃是关于只有200张图像的记忆,除非它们是超级巨大的。

答案 1 :(得分:0)

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

- (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来显示图像,这非常小。您可能希望创建一个自定义单元格,其中包含较大的图像视图(如果您想要每行多个图像,则可以并排放置几个)。

相关问题