Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 975
DemianArdus Avatar asked May 19 '14 15:05

DemianArdus


3 Answers

Override prepareForReuse method in your cell class and cancel all loadings there. Do not forget to call super

like image 90
George Petrov Avatar answered Nov 15 '22 20:11

George Petrov


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.

like image 41
Michael Dautermann Avatar answered Nov 15 '22 20:11

Michael Dautermann


Example of answer above. Swift 3

func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as! UITableViewCell).imageView.image = nil
    (cell as! UITableViewCell).imageView.sd_cancelCurrentImageLoad()
}
like image 29
Andrii Solokh Avatar answered Nov 15 '22 20:11

Andrii Solokh