Scroll上的UICollectionView滞后

时间:2015-09-24 07:32:40

标签: ios objective-c uicollectionview uicollectionviewcell

我使用UICollectionView来展示NSMutableArray中存储的一些图片

这是我的cellForItemAtIndexPath

代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    CollectionViewCell *cell = (CollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row<self.bookMarksArray.count) {
        cell.bookmarkImage.image = [self.bookMarksimages objectAtIndex:indexPath.row];
        cell.bookmarkTitle.text =[self.bookMarkNames objectAtIndex:indexPath.row];
    }else
    {
        UIImage *bookMarkImage=[UIImage imageNamed:@"emptyCell.png"];
        cell.bookmarkImage.image = bookMarkImage;
        cell.bookmarkTitle.text =@"";

    }

    cell.removeBtn.enabled = NO;
    cell.delegate = self;
    return cell;
}

我在数组self.bookMarksImages中最多有32个项目,当我滚动我的集合视图时,我会注意到滚动有一个滞后(仅适用于第一次)。

但当我更换了行 cell.bookmarkImage.image = [self.bookMarksimages objectAtIndex:indexPath.row];

带有静态图片的

cell.bookmarkImage.image = [UIImage imageNamed:@"emptyCell.png"];

我可以看到滚动没有延迟,我的收藏视图滚动顺畅。

这是我的bookmarkImage初始化代码。

-(void)getAllBookmarkImages
{
    self.bookMarksimages = [[NSMutableArray alloc] init];
    self.bookMarkNames = [[NSMutableArray alloc] init];
    NSArray *bookMarksArray = [BookMarks getBookMarks];
    for (int i=0; i<self.bookMarksArray.count; i++) {
        NSDictionary *bookmarkInfo = [bookMarksArray objectAtIndex:i];
        UIImage *bookMarkImage=[UIImage imageWithContentsOfFile:[BookMarks documentsPathForFileName:[bookmarkInfo objectForKey:@"IMAGE"]]];

        [self.bookMarksimages addObject:bookMarkImage];
        [self.bookMarkNames addObject:[bookmarkInfo objectForKey:@"TITLE"]];
    }
}

为什么数组self.bookMarksimages导致滞后?

1 个答案:

答案 0 :(得分:0)

导致此问题的因素很多

1.图像大小

2.Image Location

解决方法是借助图像路径在异步线程中加载图像。制作一个图像路径数组,而不是图像

- (void) loadImageFromPath:(NSString*)path{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
    NSData *data= [NSData dataWithContentsOfFile:path];
    UIImage *theImage=[UIImage imageWithData:data];

    dispatch_async(dispatch_get_main_queue(), ^{
        cell.bookmarkImage.imagee=theImage;
  });
     });
 }

<强>用法

[cell loadImageFromFile:[self.bookMarksimages objectAtIndex:index]];