如何根据UIImageView的高度估算UITableViewCell的高度

时间:2018-11-26 04:41:08

标签: ios swift uitableview tableview

我正在开发聊天应用程序。

我要添加图像发布功能。

以下是省略的代码。

class ImageCell: UITableViewCell {
    @IBOutlet private weak var contentImageView: UIImageView!
    @IBOutlet private weak var imageViewHeightConstraint: NSLayoutConstraint!

    func prepare(url: String) {
        contentImageView.kf.setImage(url: url) { image in 
            let height = self.contentImageView.bounds.width / image.size.width * image.size.height
            self.heightConstraint.constant = min(300, height)
            self.layoutIfNeeded()
        }
    }
}

prepare()cellForRowAt中的tableView一起被调用

但是,TableViewCell的高度变化不大。

我该如何解决?

谢谢。

P.S。

extension UIViewController: UITableViewDataSource {

    ffunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.elements.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath)
        cell.prepare(url: elements[indexPath.row].url)
        return cell
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

在单元格中的UIImageView上放置前导,顶部,底部和右侧约束。

通过heightForRow方法返回图像的高度:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return image.size.height
}
相关问题