Set UIImageView height proportional to width in UITableViewCell

I am trying to create UITableViewwhere each cell contains either a portrait or an album UIImageViewwhere the images keep the aspect ratio when filling the screen width, for example:

|        |
|########|
|########|
|########|
|########|
|########|
|        |
|########|
|########|
|########|
|        |

I set auto-detection limits to snap edges UIImageViewto the table view cell contentView. This works for width, but height is not what I want - it always expands to the full height of the main image.

I have these settings in a table view:

self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

When building a cell, I try to calculate the required height so that I can change the frame (or height limit) to UIImageView:

let cell = tableView.dequeueReusableCellWithIdentifier("activityPostCell", forIndexPath: indexPath) as UITableViewCell
let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width

let imageView = cell.viewWithTag(15) as UIImageView        
let imageViewHeight = aspectRatio * imageView.frame.width

, imageView.frame , , .

? UIImageView , ? .

+4
1

@Wain, :

let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width

let imageView = cell.viewWithTag(15) as UIImageView

imageView.addConstraint(NSLayoutConstraint(
    item: imageView, 
    attribute: NSLayoutAttribute.Height, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: imageView, 
    attribute: NSLayoutAttribute.Width, 
    multiplier: aspectRatio, 
    constant: 0)
)
+5

All Articles