簡體   English   中英

從 Firebase 異步下載后動態圖像調整大小

[英]dynamic image resizing after asynchronously downloading it from the firebase

我正在嘗試根據我從 firebase 數據庫下載的圖像動態調整圖像大小,並將其呈現在表格視圖單元格中。 我希望圖像的寬度為框架寬度和高度以進行相應調整。

我有一個 customImageView 類可以從 firebase 異步下載圖像

我嘗試了很多方法,但都是徒勞的。 有沒有一種超級干凈的方法來動態調整圖像大小:-D

這是我的手機:

class viewControllerHomeCell: UITableViewCell  { 

   @IBOutlet var mainImage: CstmImageView!

  }

我的單元格為:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellData =  TableViewControllerHome.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! viewControllerHomeCell

    cellData.mainImage.loadImagesWithUrl(from: self.postArray[indexPath.row].covrImgUrl)
  }

這是一個 UIImageView 子類,用於從 firebase 異步加載圖像。

class CstmImageView : UIImageView {
let imageCache = NSCache<AnyObject, AnyObject>()

var imageUrlString : String?
func loadImagesWithUrl(from imageUrl : String!)  {
    imageUrlString = imageUrl
    self.image = nil

    if let cachedImage = imageCache.object(forKey: imageUrl as AnyObject) as? UIImage {
        self.image = cachedImage
        return
    }

    let url = URLRequest(url: URL(string: imageUrl)!)
    URLSession.shared.dataTask(with: url) { (data, response, eror) in

        if eror != nil {
            print(eror!)
            return
        }

            DispatchQueue.main.async {
            if let downloadedImage = UIImage(data : data!) {
                if self.imageUrlString == imageUrl {
                  self.image = downloadedImage
                }
                self.imageCache.setObject(downloadedImage, forKey: imageUrl as AnyObject)
            }

        }
    }.resume()
 }
}

任何幫助都非常感謝:)

帶上你的 imageView Height Outlet 並連接你的 imageView 高度約束

class viewControllerHomeCell: UITableViewCell  { 

    @IBOutlet var mainImage: UIImageView!
    @IBOutlet var viewImageViewHeight: NSLayoutConstraint!
 }

並使用 Pod 下載圖片

吊艙'SDWebImage'

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
 {
     let cellData =  TableViewControllerHome.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! viewControllerHomeCell

        cellData.mainImage.sd_setImage(with:URL.init(string: "Pass Yor image Url string here"))
        { (image, error, imageCacheType, url) in

             cellData.mainImage.image = image

             viewImageViewHeight.constant =  image?.size.height
        }

        cellData.mainImage.loadImagesWithUrl(from: self.postArray[indexPath.row].covrImgUrl)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM