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

时间:2017-06-02 22:44:51

标签: ios swift uitableview alamofire

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

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

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

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

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

1 个答案:

答案 0 :(得分:12)

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

                }
            }
        })
        }

我希望这会有所帮助

相关问题