【问题标题】:How to estimate the height of UITableViewCell according to the height of UIImageView如何根据 UIImageView 的高度估计 UITableViewCell 的高度
【发布时间】:2018-11-26 04:41:08
【问题描述】:

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

我想添加图片发布功能。

以下为省略代码。

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()cellForRowAttableView 一起调用

但是TableViewCell的高度变化不大。

我该如何解决?

谢谢。

附言

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
    }
}

【问题讨论】:

  • 您能在此处添加您的 Tableview 数据源和委托方法吗?
  • 如果我们想要动态的单元格高度,那么需要的图像是aspect ratiowidth
  • @HPM 你好,我添加了一个数据源方法!
  • @touyu,我让你添加 Tableview 委托而不是 UICollectionview!。已设置 tableview.estimatedrowheight = #YOUR_ESTIMATED_HEIGHT# 和 tableview.rowheight = .automatic
  • 简单的回答没有heightForRowAt是不可能的

标签: ios swift uitableview tableview


【解决方案1】:

在单元格中对 UIImageView 设置前、上、下、右约束。

在heightForRow方法中返回图片的高度:

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

【讨论】:

  • 如果当时没有图片怎么办!!
  • 在这种情况下,您应该使用默认的临时高度,例如 100。并在下载图像时重新加载表格单元格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多