0
votes

I have a TableView whose first element is a fixed aspect ratio header image. I embedded a UIImageView inside the UITableViewCell's Content View. The desired outcome is the entire cell adopting the size of the image. I tried a couple of things, first of all, pinning all four edges of the UIImageView to the parent Content View and setting the aspect ratio to my desired value (2h by 3w). With this setup the aspect ratio constraint gets completely ignored and the image view takes up the height of the cell, which shrinks my asset. Next, I tried to remove the bottom constraint. As a result, the aspect ratio is respected, but the cell height is larger than that of the image view.

My question is, can I make the cell shrink to wrap the height of the image view using auto layout?

1

1 Answers

0
votes

Can I make the cell shrink to wrap the height of the image view using autolayout?

Yes you can, but there is a trick. UITableViews have a fixed height for all their cells. If you want variable height you must implement UITableViewDelegate method

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

If your cell constraints are properly setup (and by that I mean if instead of a cell you had a UIView, it's size would be defined by it's content), you will be able to do something like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:kIdentifier];
// setup your cell image
return [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}

The problem is, if you are retrieving the images from the web, there is no possible way that you know the size of the image without loading it. If you are using local images, this should work.