Dynamic cell height with async images in Swift 2

1.1k Views Asked by At

I'm trying to build a Facebook-like feed. I'm using a standard Tableview with autolayout constraints set up in storyboard.

The width should be 100% of the viewport and the height according to the aspect ratio of the image.

I'm using Haneke's hnk_setImageFromURL for async image loading from the server.

I saw here the option to use tableview.beginUpdates() or endUpdates() and it causes the first render to work alright, but once I start scrolling the height calculation goes wrong, cells appear blank and/or the app crashes due to indexOutOfBounds.

Is manually calculating the height in heightForRowAtIndexPath with pre-given aspect ratio from the server the only option?

My relevant part of the code

ViewController:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 500
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

      let cell = tableView.dequeueReusableCellWithIdentifier("FeedItem", forIndexPath: indexPath) as! FeedItemTableViewCell

      content.hnk_setImageFromURL(NSURL(string: contentImage)!, placeholder: nil, format: nil, failure: nil, success: {image in

                    cell.content.image = image  
                    self.beginUpdates()
                    self.endUpdates()

                }
        )
}

P.S. A side effect caused by using Haneke is that I have to provide some initial size to the UIImageView, currently I'm using a placeholder image which causes irritating animations when the image is loaded from the server

1

There are 1 best solutions below

1
On

Here instead of loading cell data in the cellForRowAtIndex method,I have created a subclass of TableViewCell. And I have used SDWebImage instead of Haneke.

Hope this helps