1
votes

I have stretched images displayed in TableViewCell. I need to find the height and width of image from image URL. I need to find the aspect ratio and fit the image on the cell according to the height of dynamic cell in Swift 4.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.ManCell) as! ManCell
    let image = self.posts[indexPath.row]["thumbnail_images"]["medium_large"]["url"].stringValue

    let cleanString = removeHtmlTagsFromResponse(index: indexPath.row)
    cell.nutriTitle.text = self.posts[indexPath.row]["title"].stringValue
    print("labels: \(self.posts[indexPath.row]["title"].stringValue)")

    cell.nutriDetail.text = cleanString
    let lCount = calculateHeightOfLable(cellLabel: cell.nutriDetail)
    print("string: \(cleanString)")
    print("HeightCount: \(lCount)")
    cell.nutriImage.sd_setImage(with: URL(string: image), placeholderImage: UIImage(named: "no_image"))
    let heightContentSize = cell.bounds.height
    print("HeightContentSize= ",heightContentSize)
    return cell
}
1

1 Answers

0
votes

It looks like you are using SDWebImage to load your images from a URL. In the documentation you will find that there is another method on UIImage called: sd_setImageWithURL:placeholderImage:options:completed: which takes a completion handler with 4 parameters: image: UIImage, error: NSError, isCache: Bool, and url: URl. Use the first parameter to get the size of the image. Note that this is asynchronous; you don't get the size until the image is downloaded (assuming you don't already have it in the cache), so then cell may resize if you are dynamically sizing it.