Tutorial 3: My Locations. Solution to Exercise at p. 225

This is my solution to the Exercise at p. 225 to make the height of the photo table view cell dynamic, depending on the aspect ratio of the image.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    case (1, _):
        return imageView.isHidden ? 44 : calculateRowHeight()

func calculateRowHeight() -> CGFloat {
    let aspectRatio = image!.size.width / image!.size.height
    let height = 260 / aspectRatio
    imageView.frame.size.height = height
    return height + 20

The above code should mostly work but why is the value of 260 hard coded in the calculation for height? How would that work/look on an iPad for example?

I am working here from memory and so might be missing something there that’s obvious. If so, please disregard the question :smiley:

The requirement was that the width of the imageView is 260 with image aspect fill that leads to height height calculation to that number.

It’s possible to calculate width dynamically too from the bounds width size of parent view UITableViewCell. but it was beyond the exercise task.

If the requirements was for a static width of 260, then yes, your code should work great!

This topic was automatically closed after 166 days. New replies are no longer allowed.