Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First off, I'd highly recommend using <a href="https://github.com/rs/SDWebImage" rel="nofollow">SDWebImage</a> for the asynchronous downloading, if you're not already doing so. Depending on what you want, you can have it cache images in memory or on disk - the latter is done in the correct fashion, by saving them in the special cache folder, so iOS can delete them if it runs out of space. It also provides a handy category on UIImageView, similar to what AFNetworking gives you, but with more options and and an optional completion block. That way you can do something like this:</p> <pre><code>#import &lt;SDWebImage/UIImageView+WebCache.h&gt; ... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Create the cell... [cell.myImageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { if (image != nil) { [self.images insertObject:image atIndex:indexPath.row]; [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES]; } }]; return cell; } </code></pre> <p>That way you download the image asynchronously, set the UIImageView correctly, but you also use the block to save the image in an NSMutableArray, so you can tell the tableview the correct height. It also tells the table view to update the height of the cell whose image has loaded. Then when the table view needs to know how high a given cell is, if the image has been loaded, we'll get the size from it:</p> <pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { id image = [self.images objectAtIndex:indexPath.row]; if ([image isKindOfClass:[NSNull class]]) { return defaultHeight; } else { return [image size].height + topPadding + bottomPadding; } } </code></pre> <p>That way we know the height even of images that are off-screen (e.g. when you have scrolled to the bottom). This solution assumes that you start by populating the NSMutableArray with NSNull values, which are then replaced with the images when they load. Finally, if you like, you could use SDWebImageManager to start the downloads manually even before the cells are shown.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload