I\'ve been struggling with fitting an UIImageView
which shows images of variable widths and heights with Aspect Fill
. The cell height is not adapting t
Suppose you have an UIImage
with dimensions 768 x 592 of width
and height
respectively, the height always remains equals, where the device it's rotated for example in the dimensions above (iPad), the width
of the image change to 1024 and the height
remains equal.
What you can do to maintain the aspect of the image is scale it in the dimensions you want, for example if you know that the images coming always have the same dimensions, we say for example 1280x740 , you can set the UIImage
to .ScaleToFill
and calculate in the following way:
(widthOfTheImage / heightOfTheImage) * heightWhereYouWanToSet = widthYouHaveToSet
For example :
(1280 / 740) * 592 = 1024
And it's the width
I have to set in my UIImage
to maintain the proportions of the image when it's change it's width.
I hope you understand where I try to say to you.
I cobbled together a solution based on two previous answers:
I wanted to keep the AspectRatio
of the image regardless of its Height
while fixing up the Width
according to that of the UIImageView
, the container of the image.
The solution comprises of :
Adding a new AspectRatio
constraint
let image = UIImage(ContentFromFile: "path/to/image")
let aspect = image.size.width / image.size.height
aspectConstraint = NSLayoutConstraint(item: cardMedia, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: cardMedia, attribute: NSLayoutAttribute.Height, multiplier: aspect, constant: 0.0)
when adding this constraint, xCode will complain about the new "redundant" constraint and attempt to break it, rendering it useless, yet displaying the image exactly like I want. This leads me to the second solution
Lowering the priority of the new constrain to '999' seems to stop xcode from breaking it, and it stopped showing warning message about the new constraint
aspectConstraint?.priority = 999
Not sure why xCode automatically adds UIView-Encapsulated-Layout-Height
and UIView-Encapsulated-Layout-Height
at build/run time; however, I learned how to respect that and live with it :)
Just leaving the solution here for anyone to check. This is working on iOS 8. I tried with iOS7 but it doesn't work the same as you need to implement tableView:heightForRowAtIndexPath
calculating the height of the cell based on all the items contained within it and disable setting up:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0