【问题标题】:Swift - Dynamic UITableViewCell size based on image aspect ratioSwift - 基于图像纵横比的动态 UITableViewCell 大小
【发布时间】:2017-11-04 10:10:07
【问题描述】:

我正在尝试创建动态大小的 UITableViewCells,根据从服务器下载的图像的纵横比更改高度。

例如,如果图像的高度是其宽度的两倍,我希望 UITableViewCell 的高度是屏幕宽度的两倍,以便图像可以占据屏幕的整个宽度并保持纵横比。

我尝试做的是向单元格添加约束并使用 UITableViewAutomaticDimension 来计算高度,但我面临的问题是在下载图像之前我无法知道图像的纵横比,因此单元格开始时很小,然后一旦手动刷新 tableView,单元格就会以正确的大小出现。

我不觉得在下载图像时重新加载每个单独的单元格也是一种好方法。

这种方法是最好的方法吗?我一辈子都想不出还有什么办法做到这一点,因为在初始化单元格时我无法知道单元格本身的纵横比。

【问题讨论】:

  • 您可以将图像宽度和高度发送到服务器,然后在返回时您可以根据图像提供单元格宽度和高度。

标签: ios swift uitableview alamofire


【解决方案1】:

为了实现这一点,我首先使用字典[Int:CGFloat] 来保留计算出的单元格高度,然后在heightForRowAtIndexpath 方法中使用保存在字典中的值,在您的cellForRowAtIndexpath 方法中,您应该下载您的图像,计算纵横比,将您的单元格宽度或图像宽度乘以您的纵横比,然后将在对应的 IndexPath 数字中计算的高度放入您的字典中

在类似这样的代码中,这是一个使用 alamofire 加载图像的代码示例

    var rowHeights:[Int:CGFloat] = [:] //declaration of Dictionary


    //My heightForRowAtIndexPath method
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = self.rowHeights[indexPath.row]{
            return height
        }else{
            return defaultHeight
        }
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

if let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as? ImageCell
        {
        let urlImage = Foundation.URL(string: "http://imageurl")
        cell.articleImage.af_setImage(withURL: urlImage, placeholderImage: self.placeholderImage, filter: nil, imageTransition: .crossDissolve(0.3), completion: { (response) in

            if let image = response.result.value{
                DispatchQueue.main.async {

                    let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
                    cell.articleImage.image = image
                    let imageHeight = self.view.frame.width*aspectRatio
                    tableView.beginUpdates()
                    self.rowHeights[indexPath.row] = imageHeight
                    tableView.endUpdates()

                }
            }
        })
        }

希望对你有帮助

【讨论】:

  • 我已经尝试过你的解决方案,但是当我滚动时,我的 tablview 正在跳舞......你能帮忙@Reinier
  • 每当我滚动时,我的 tableview.content.size 都会发生变化,这会导致延迟行为。
  • @AbhijitHadkar 你能发个视频链接吗?
  • 没有 tableview.beginupdates() 和 tableview.endupdates() 它的工作没有弹跳
  • 好的,@AbhijitHadkar 我会尽快审核,感谢您的反馈
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2021-05-10
  • 2017-08-10
  • 2012-07-05
  • 2013-06-26
  • 2012-04-15
相关资源
最近更新 更多