Swift - 基于图像宽高比的动态UITableViewCell大小

dan*_*tin 5 uitableview ios swift alamofire

我正在尝试创建动态大小的UITableViewCells,根据从服务器下载的图像的宽高比来改变高度.

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

我试图做的是添加约束到单元格并使用UITableViewAutomaticDimension来计算高度,但我面临的问题是我无法知道图像的宽高比,直到下载,因此单元格开始小,然后手动刷新tableView后,单元格显示正确的大小.

我不想在下载图像时重新加载每个单元格也是一种很好的方法.

这种方法是最好的方法吗?我不能为我的生活思考如何做到这一点,因为我在初始化时无法从细胞内部知道纵横比.

Rei*_*ian 13

为了达到这个目的,我首先使用字典[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()

                }
            }
        })
        }
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

  • 我曾尝试过您的解决方案,但滚动时我的tablview正在跳舞...您能帮忙@Reinier (2认同)