1

I'm trying to create table cell with dynamic size, specifically height. Cell contains 4 lines of text and image view. Image inside the image view usually have big resolution, so it should be scaled to fit into the image view. I used aspectFit mode for scaling inside image view.

Cell layout

If I hardcode cell height, image view receive extra space(highlighted with color)

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 500
}

Horizontal image

To remove extra padding i need to calculate image dimensions after scaling. How can i do that in Swift?

Also i tried UITableViewAutomaticDimension, but the cell size become huge(depends on image resolution) as cells dimensions were calculated based on full resolution image, but not on scaled (with aspectFit mode)

Another solution was provided in this answer, but performance of this solution is very poor and unacceptable for table view. I believe there is better solution as image already scaled by system to fit the width, i just need to know the dimensions of scaled image.

Community
  • 1
  • 1
Jurasic
  • 1,845
  • 1
  • 23
  • 29

2 Answers2

0

After posting the question, new idea had come to mind. If scaling mode is always aspectFit and cell width is always the same, so knowing that i can calculate scaled factor. After that can calculate cell height:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    // current cell height = 4 text lines + scaled image

    // Number of text lines
    let numberOfTextLines: CGFloat = 4.0
    // Line height of font used in text labels
    let textLineHeight = UIFont.systemFont(ofSize: 17).lineHeight
    // Size of image to show in cell
    let imageSize = imageRecords[indexPath.row].image!.size
    // Scale factor: cell width to image width
    let scale = self.tableView.bounds.width / imageSize.width

    // Cell height = sum of all lines height + scaled image height
    return (numberOfTextLines * textLineHeight) + (scale * imageSize.height)
}

To improve cell height precision, cell margins should be taken into account.

Jurasic
  • 1,845
  • 1
  • 23
  • 29
0

UITableViewAutomaticDimension will get you what you want, if the constraints are set correctly. Screenshot alone makes it hard (sharing the storyboard/xib helps!), but you probably want to do the following based on what I see:

  • Remove the bottom constraint on the image view
  • Add a constraint from the bottom of the content view to the bottom of the image view
  • Use UITableViewAutomaticDimension

Performance can still suck in some cases with automatic dimension, but give it a shot.

Ben
  • 1,117
  • 13
  • 21
  • Unfortunately, constrain from bottom of the content view to the bottom of the image view gives the same row height on UITableViewAutomaticDimension as vice versa constrain. Padding size stayed the same as before. – Jurasic Feb 03 '17 at 10:34