2017-06-02 75 views
2

我试图创建动态大小的UITableViewCells,根据从服务器下载的图像的宽高比更改高度。例如,如果图像的高度是其宽度的两倍,那么我希望UITableViewCell的高度是屏幕宽度的两倍,以便图像占用屏幕的整个宽度并保持高宽比。Swift - 基于图像宽高比的动态UITableViewCell大小

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

我不想重新加载每个单独的单元格时,它的图像下载是一个伟大的方式来做事情。

这种方法是最好的方法吗?我不能为我的生活考虑如何做到这一点,因为当它初始化时,我不知道单元内部的宽高比。

+0

您可以将图像宽度和高度发送到服务器,然后在返回时可以相应地为图像指定单元格宽度和高度。 –

回答

6

为了实现这一点,我先用一本字典[Int:CGFloat]保持细胞的计算heigths然后在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() 

       } 
      } 
     }) 
     } 

我希望这一点帮助

相关问题