首页 文章

如何优化从URL中加载图像以进行uicollectionview? [关闭]

提问于
浏览
1

我不知道uicollection视图总是调用方法 **(UICollectionViewCell *)collectionView:(UICollectionView )collectionView cellForItemAtIndexPath:(NSIndexPath )indexPath

当你移动单元格时,我的程序总是调用从url加载图像 . 慢慢来 .

3 回答

  • 4

    您可以将SDWebImage用于缓存支持 . 您无需下载之前已提取的图像 .

    只需访问https://github.com/rs/SDWebImage并使用它 .

  • 1

    使用 [NSURLConnection sendAsynchronousRequest:queue:completionHandler: 加载图像,然后使用NSCache防止反复下载相同的图像 . 在这里查看示例,您甚至可能希望包含此AFNetworking库并使用它:https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/UIImageView%2BAFNetworking.m

  • 1

    来自Apple的Documentation ......

    – dequeueReusableCellWithReuseIdentifier:forIndexPath:
    

    当系统要求为集合视图提供新单元格时,请从数据源对象中调用此方法 . 如果现有单元格可用,则此方法会使现有单元格出列,或者根据先前注册的类或nib文件创建新单元格 .

    Important :在调用此方法之前,必须使用registerClass:forCellWithReuseIdentifier:或registerNib:forCellWithReuseIdentifier:方法注册类或nib文件 .

    EDIT :我假设您正异步加载图像,如果没有,则使用以下代码 .

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
      UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
      [NSURL URLWithString:@"ur image url"]]]];
      dispatch_sync(dispatch_get_main_queue(), ^{
         [[cell imageView] setImage:image];
         [cell setNeedsLayout];
      });
      });
    

    EDIT 2 :atomk 's suggestion(below comment) makes sense,so i won' t在这里发布代码 . 在替换中你可以使用名为SDWebImage的库 . 你可以加载你想要的任意数量的图像,并且根据代码的作者不会多次下载相同的URL .

相关问题