简体   繁体   English

使用GCD从设备加载UICollectionViewCell异步图像,

[英]UICollectionViewCell asynchronous image loading from device using GCD,

I have a collection view that needs to display a collection of images whose files are saved on the device. 我有一个收集视图,该视图需要显示图像的集合,这些图像的文件保存在设备上。 They are all 600x600 pixels so I thought it would be better to create the UIImage asynchronously on a background thread and then set the image property of my UIImageView on the main thread. 它们都是600x600像素,所以我认为最好在后台线程上异步创建UIImage,然后在主线程上设置UIImageViewimage属性。 Below is where I do this in my (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath method 下面是我在(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath方法中执行此操作的位置

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        NSString *imageName = [NSString stringWithFormat:@"wo-%@", template.fileName];

        UIImage *image = [UIImage imageNamed:imageName];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (image == nil)
            {
                self.collectionView.backgroundColor = [UIColor redColor];
                NSLog(@"image named: %@ in nil!", imageName);
            }
            cell.imageView.image = image;
        });
    });

    return cell;

Every once in a while image will be nil for one of the cells. 每隔一段时间,其中一个单元的imagenil It isn't reproducible and it's not always the same cell/image name. 它是不可复制的,并且不一定总是相同的单元格/图像名称。 I was wondering if this has anything to do with using the UIImage imageNamed: method or am I using GCD incorrectly? 我想知道这是否与使用UIImage imageNamed:方法有关,还是我使用GCD的方式不正确? Any thoughts on the issue would be appreciated. 对此问题的任何想法将不胜感激。

For loading image asynchronously "SDWebImage" could be a best solution. 对于异步加载图像,“ SDWebImage”可能是最佳解决方案。

SDWebImage SDWebImage

just call the following method in your cellForItemAtIndexPath: 只需在cellForItemAtIndexPath中调用以下方法:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.example.com/path/to/image.jpg"]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM