Swift TableView用SDWebImage4.3.0加载图片时复用单元格显旧图求助
Hey there! I’ve dealt with this exact annoying issue before—when UITableView cells reuse, the old image sticks around until the new one loads. Let’s walk through the fixes that worked for me with SDWebImage 4.3.0:
1. Cancel Pending Image Requests First
When a cell gets reused, there might still be an unfinished image request from its previous use. If that old request completes after you start the new one, it’ll overwrite the correct image. Stop that from happening by canceling the current load before setting up the new one:
Swift
cell.imageView?.sd_cancelCurrentImageLoad()
Objective-C
[cell.imageView sd_cancelCurrentImageLoad];
2. Reset the ImageView Before Loading the New Image
Even after canceling the request, the imageView might still hold the old image. Clear it out (or set a placeholder) to avoid that flash of old content:
Swift
// Option 1: Set to nil cell.imageView?.image = nil // Option 2: Use a placeholder image cell.imageView?.image = UIImage(named: "default-placeholder")
Objective-C
// Option 1: Set to nil cell.imageView.image = nil; // Option 2: Use a placeholder image cell.imageView.image = [UIImage imageNamed:@"default-placeholder"];
3. Load the New Image with SDWebImage
Now you’re ready to load the correct image. Use sd_setImage(with:placeholderImage:) to handle the async load gracefully:
Swift
if let imageUrl = URL(string: yourImageUrlString) { cell.imageView?.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "default-placeholder")) }
Objective-C
NSURL *imageUrl = [NSURL URLWithString:yourImageUrlString]; [cell.imageView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:@"default-placeholder"]];
4. (Pro Tip) Handle Reset in prepareForReuse
For cleaner code, move the cancel/reset logic into your custom UITableViewCell’s prepareForReuse method. This way, every time a cell is reused, it automatically cleans up after itself without cluttering your cellForRowAt method:
Swift
class CustomTableViewCell: UITableViewCell { override func prepareForReuse() { super.prepareForReuse() self.imageView?.sd_cancelCurrentImageLoad() self.imageView?.image = UIImage(named: "default-placeholder") } }
Objective-C
@interface CustomTableViewCell : UITableViewCell @end @implementation CustomTableViewCell - (void)prepareForReuse { [super prepareForReuse]; [self.imageView sd_cancelCurrentImageLoad]; self.imageView.image = [UIImage imageNamed:@"default-placeholder"]; } @end
Putting all these steps together should eliminate that annoying old image flash. The key is to cancel any in-flight requests and clear the existing image before starting the new load—SDWebImage handles the rest smoothly!
内容的提问来源于stack exchange,提问作者Eric Chong

