1

I am replicating the effect in the image below. I created a custom UITableViewCell class with an UIImageView property. I set the prototype cell to my custom class. However, I cannot get the table cell's height to resize to the height of the image. There is always space above and below the image.

enter image description here

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
Walter M
  • 4,993
  • 5
  • 22
  • 29

3 Answers3

0

You can make the heigh of your UITableViewCell dynamic regarding the height of your image. The UITableViewDelegate has a function entitled tableView:estimatedHeightForRowAtIndexPath: that according to Apple:

Asks the delegate for the estimated height of a row in a specified location.

Then you can in your method ask for the height of the UIImageView and set the height for the row properly, see the following example:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return self.getEstimatedHeightForImageAtIndex(indexPath.row)
}

func getEstimatedHeightForImageAtIndex(row: Int) -> CGFloat {
    // here you need to get the height of image for the selected row.
}

There is a nice tutorial you can read to know more about the topic :

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
0

What I did was to create a custom UITableViewCell, added an UIImageView to the cell and resized it in the storyboard to fill the whole cell.

If you do that though, make sure you add the constraints to have it horizontally and vertically centred, and add the spacing constraints, but change the spacing not to margin (uncheck the box).

See the image below:

enter image description here

And another thing to remember is the content mode of the imageview. I learned a lot from @EmptyStack and @erkanyildiz answers to this question.

I hope you found any of this useful, and I am sorry if none of it helped! :)

Community
  • 1
  • 1
Septronic
  • 1,156
  • 13
  • 32
0

Create a custom UITableViewCell, set cell style to custom in storyboard. Add an UIImageView to the cell and resize image to fill the whole cell. Add image outlet to your custom UITableViewCell and use that outlet when seting an image in your TableViewController.

In your viewDidLoad() function add tableView.rowHeight = UITableViewAutomaticDimension

Then you need your image aspect ratio (width / height) so you can use it when you set your row height.

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath 
indexPath: NSIndexPath) -> CGFloat {
  return view.frame.width / CGFloat(aspectRatio)
}