Reputation: 301
So I have been trying to adjust the size of my tableView Cells according to the size of an image that I get from an API call that I make.
https://i.sstatic.net/iKjzK.jpg
The images that I get are in a 5:4 ratio. What i've done in the screenshot is put a fixed height under
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let viewWidth = self.view.frame.size.width
let imageHeight = (viewWidth * 5) / 4
return imageHeight
}
(I've ignored small things like cell Paddings and stuff)
Even though the image doesn't look too bad, i'm not happy with what i've done. I have also tried
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if image != nil {
return image.size.height
} else {
return DEFAULT_HEIGHT
}
}
Which gives me a cell size where the image's height is being stretched. What is the correct way to do what i'm trying to achieve?
EDIT: I wanted to find a way so that the image automatically adjusts itself.
For example, Right now, the images that I receive from the backend are in the ratio 4:5. Hypothetical situation if they change it to a 1:1 ratio, I would want it to adjust itself. Any suggestion? Also, my storyboard is going bonkers when i add the aspect ratio. TIA!
Upvotes: 0
Views: 278
Reputation: 2994
Why don't you use Autolayout for your cell, put the ImageView inside the cell and give it trailing and leading constraints of 0(or your margin) and an aspect ratio constraint of 5:4?
Upvotes: 1