Search code examples
iosuitableviewsdwebimage

SDWebImage + UITableViewCell, wrong image when scrolling?


i'm having an issue using SDWebImage to load images to a UIImageView inside a custom UITableViewCell. This is my code at the UITableView delegate:

    static NSString *userTableId = @"userTableId";
    UserDetailsTableViewCell *cell = (UserDetailsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:userTableId];
    NSDictionary *user = [userList objectAtIndex:indexPath.row];
    NSInteger position = indexPath.row + 1;
    [cell.userDetailsView loadFromDictionary:user WithIndex:position ForCharitie:false];
        cell.userDetailsView.delegate = self;

    cell.userDetailsView.delegate = self;
    return cell;

And here is my code for loadFromDictionary:

-(void) loadFromDictionary: (NSDictionary *) dic  WithIndex: (NSInteger) index ForCharitie: (BOOL) isCharitie{
    NSDictionary *userImageDic = [dic objectForKey:@"image"];
    NSString *url =[userImageDic objectForKey:@"url"];

    [userImage setImage:[UIImage imageNamed:@"defaultAvatar"]];
    if ([url class] != [NSNull class]){
        [userImage setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
    }
}

Now, the problem is if i scroll down before some images finish loading. For example, let's say I see the first 8 rows, and rows 1, 2 and 3 still loading their images, now i scroll to 9-16, i see the defaultAvatar for all of them, and after a few seconds (i guess when images of rows 1,2 and 3 finish downloading), the images on cells 9, 10 and 11 change to the ones that belong to 1,2 and 3. I don't know if there is a way to stop the images from downloading when i reuse the cell, or something like that. Thank you and sorry for my English!


Solution

  • If you have your UITableViewDelegate set on your table, you could use the delegate method:

    - tableView:didEndDisplayingCell:forRowAtIndexPath:

    to set the image to NULL (or the default) when your cell scrolls off screen.

    And since you're using SDWebImage, canceling it could be as easy as "cancelCurrentImageLoad" on the cell's image view.