2017-06-02 78 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() 

       } 
      } 
     }) 
     } 

我希望這一點幫助

相關問題