Images in UITableView keep re-loading and wrong images flash while scrolling

前端 未结 6 1204
醉酒成梦
醉酒成梦 2021-01-16 19:40

i have created a UITableView which populates each cell from URL requests. I have used \'dispatch_queue\' to prevent the UItableView from freezing. For some reason when i s

6条回答
  •  别那么骄傲
    2021-01-16 20:45

    When you scroll your table every time your image will download again. to prevent this i prefer you to get image from cache and set in your imageview directly. so as per your code. if you scroll from 0 index to 10 then cell will download image for all 10 cells. after that if you scroll again 10 to index 0 . then image will be download again.

    you can use (https://github.com/rs/SDWebImage) to download image async. its very easy and fast.

    i prefered this library because it will handle your cache. just write below code

    #import "UIImageView+WebCache.h"
    
    // in cellForRowAtIndexPath.
    [customCell.customCellImageView sd_setImageWithURL: [NSURL URLWithString:urlString]];
    

    remove below code.

    dispatch_queue_t imageQueue = dispatch_queue_create("imageDownloader",nil);
        dispatch_async(imageQueue, ^{
    
            NSData *data = [[NSData alloc] initWithContentsOfURL:urlString];
    
            dispatch_async(dispatch_get_main_queue(), ^{
    
                customCell.customCellImageView.image = [UIImage imageWithData: data];
            });
        });
    

    Maybe this will help you.

提交回复
热议问题