1
votes

I want to display image in cell, and because I need to download it first so I would like to display (for question simplicity) black view with the same width and height like image should be displayed.

Because I want to stretch image to same width as cell width, I only need aspect ratio for setting height and this is provided in my code when cellForRowAt is called.

I decided to achieve "black view" before downloading image I only need one UIImageView with black background, and resizing it when cellForRowAt is called. But here is the problem, because using code from similiar questions is not working for me.

I tried something like this in cellForRowAt method:

var frame cell.imageView.frame
frame.size.height = CGFloat(aspectRatio) * frame.size.width
cell.imageView.frame = frame

EDIT

As a result I want something like facebook, where we have photo with the same width as cell and height accordingly to aspect ratio. For simplicity cell can only have UIImageView.

2
Are you using autolayout? - Dheeraj D
Yes, I'm using autolayout - Tajnero
So why are you doing this programmatically? - Dheeraj D
But how can I set specific aspect ratio of UIImageView if there is now image inside, only black background? - Tajnero
You can set uiimageview background color to black and when you get image change its background color to clear color and set your downloaded image - Dheeraj D

2 Answers

0
votes

Since you're using auto layout, in the storyboard you should set two things:

  • First, set the width of the UIImageView to be the full width of the cell
  • Second, set the aspect ratio of the UIImageView to 1:1 - this says the height is always the same as the width.

If you're using the UITableView's Automatic Dimensions for cell heights, this should be all you need; no code anywhere, everything else is as normal.

If you're not using the automatic cell height feature, then either set the cell height once with self.tableView.rowHeight = self.tableView.bounds.size.width if they're all the same, or, if the cells can be different heights:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

    if (<indexPath IS IMAGE ROW>) 
        return tableView.bounds.size.width
    return <default height>
}

Where I've written <indexPath IS IMAGE ROW>, you should replace that with whatever condition you need to detect if this particular cell is an image type. Also, as Rikh pointed out, where I've written <default height>, you should replace that with the height of the cells that are not the image type. Of course, you may have a much more complex design for your table; this just covers the case you were asking about.

-1
votes

here my solution

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentMode.ScaleAspectFit;
}