iosiphoneswiftuitableviewheightforrowatindexpath

heightForRowAtIndexPath Not working properly


I am trying to display an image with a correct aspect ratio in my tableView. I have pre-calculated the aspect ratio of the image, and it seems to work properly on the actual image, but not on the cell it is displayed in.

Code for image in cell:

private var cellImage: UIImage? {
        get { return cellImageView.image }
        set {
            cellImageView?.image = newValue
            if let newimage = newValue {
                heightConstraint.constant = newimage.size.width / CGFloat(aspectRatio)
            }
        }
    }

Code in tableView:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
            return tableView.bounds.size.width / CGFloat(aspectRatio)
    }

aspectRatio is a variable that is the same in both. aspectRation = width/height of image. Also, I checked to see that the height received in both places is the same, and they are the same value (in runtime).

Anyone know why the cell height is not set correctly?


Solution

  • You can use dynamic cell height and make cell fit to imageView inside it Check this tutorial https://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift