如何找到图像的高度和宽度,并使tableviewcell具有高宽比?

时间:2018-11-29 08:54:56

标签: ios swift image uitableview

我已经拉伸了TableViewCell中显示的图像。我需要从图像URL查找图像的高度和宽度。我需要找到长宽比,并根据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 个答案:

答案 0 :(得分:0)

您似乎正在使用SDWebImage从URL加载图像。在文档中,您会发现UIImage上还有另一个方法:sd_setImageWithURL:placeholderImage:options:completed:,该方法带有一个带有4个参数的完成处理程序:image:UIImage,错误:NSError,isCache:Bool和url:URl。使用第一个参数获取图像的大小。注意,这是异步的。在下载图片之前,您不会得到大小(假设您尚未将其保存在缓存中),因此,如果您动态调整其大小,则可能会调整单元格的大小。