iosswiftuiimageviewuiimageheightforrowatindexpath

Set UITableViewCell height to UIImage height?


I have a custom TableViewCell, and i want its height to match the size of the UIImage. The UIImageView in the Cell is set to aspect fit, and i want the UIImageview to be as high as the UIImage it contains, and the width to be equal to the width of the table view (screen width). In the method heightForRowAtIndexPath: I have the image that the cell at a given indexPath.row contains. The cells are configured that way, that if i set the heightForRowAtIndexPath to let's say 500, the imageview is the only view that will get stretched.

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let image = comics[indexPath.row].image

        return image.size.height + 103
}

the 103 are the points that make the rest of the cell height (buttons and a label)(see sceenshot).

Now the problem: all cells are too hight! and as if this wouldnt be strange enough, some of them are too short??? (picture) And i have read a lot similar posts but none of them answers my question. Somehow the image.size.height is larger than the actual image in the imageview?? I just want the uiimageview to be the same size as the image in it, in mode AspectFit.

Do you have any ideas on this? If you have any further questions pleas ask me! Thank you! Screenshot


Solution

  • Thank you so much guys! The thing with the aspect ratio did it:

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
            let image = comics[indexPath.row].image
            let aspectRatioImg = image.size.height / image.size.width
    
            return view.bounds.width * aspectRatioImg + 103
        }