UIcollectionView has slow jerky loading of images

2019-06-14 14:15发布

问题:

I have a UICollectionView with some images in it. It is very slow and jerky to load the images on the first scroll down. After that, when the images are loaded it is fine.

I guess the problem is that the images don't get loaded until the cell reaches the screen which causes a lag. I'm assuming what I need to do is load the images before they appear on the screen. I'm not sure how to do this and am obviously searching for the wrong thing as I can't find any answers. Please can someone point me in the right direction please??

Here is the code which loads the images...The images are in my app not downloaded or anything.

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [[cell myImage]setImage:[UIImage imageNamed:[arrayOfImages objectAtIndex:indexPath.item]]];

    return cell;
}

Thanks!

回答1:

Look at this answer

Add these 2 lines after your dequeue

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;


回答2:

Even though you are not downloading the images, loading from permanent storage is still too slow to do during scrolling, as you've discovered. Try treating the +imageNamed: call as if it was a download, which will make the code more complex, but fix the responsiveness. The answers to other questions like Poor UICollectionView Scrolling Performance With UIImage might help.



回答3:

Just fetch the contents and store it in an array asynchronously. And do only the assigning part from within the delegate method. If you want to display all the cells at once, place a sample thumbnail image and replace it with the original when the array gets the real image. Else, you could reload the collection view each time the array gets an object, such that the collection view's cell count increases gradually as the images get fetched.