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

前端 未结 6 1206
醉酒成梦
醉酒成梦 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:25

    The reason for this is the UITableView is reusing the cells created. So firstly it creates lets say 10 of your CustomCell class.

    Cell 0
    Cell 1
    ...
    Cell 9

    By creating these 10 cells it will initiate 10 async calls to fetch images.

    block 0 -> Cell 0
    block 1 -> Cell 1
    ...
    block 9 -> Cell 9

    This will work fine if you don't scroll until all 10 downloads have finished.

    But as soon as you start scrolling, the UITableView will start reusing the cells created and initiate new downloads.

    So first it might reuse Cell 0 and create block 10 -> Cell 0.

    If block 0 was not finished when Cell 0 was picked for reuse, you will now have two blocks wanting to put their image onto the same cell. Leading to the following two scenarios:

    1. Block 0 finishes first, then block 10
    2. Block 10 finishes first, then block 0

    This is what is causing the "flashing".

    Then imagine scrolling through 1000s of cells within seconds :)

    Solution

    You need to be able to cancel the queued block for your cell being reused.

    I would use e.g. SDWebImage or FastImageCache.

提交回复
热议问题