UITableViewCell load images and reused cells

后端 未结 2 917
情深已故
情深已故 2020-12-18 05:25

i need to load from web/files some UIImages. I was searching and i found in other question this code:

    if (![[NSFileManager defaultManager] fileExistsAtPa         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 05:43

    You are loading image asynchronously, so during fast scrolling cells get reused faster then images are downloaded. One way to avoid loading a wrong image, would be to check if cell already got reused when image is loaded. Or cancel all requests in progress when you dequeue new cells.

    I would also recommend to look at AFNetworking, as it contains helpful category for UIImageView, so you can do something like this:

    [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
    

    It also contains cancelImageRequestOperation method, to cancel requests in progress. Then your code will look like this:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    } else {
        [cell.imageView cancelImageRequestOperation];
    }
    [cell.imageView setImageWithURL:[NSURL URLWithString:user.imageURL] placeholderImage:[UIImage imageNamed:@"xger86x.jpg"]]; 
    

提交回复
热议问题