簡體   English   中英

將SDWebImage用於帶有可選圖像URL的UITableViewCell

[英]Using SDWebImage for UITableViewCell with optional image URL

我正在嘗試使用SDWebImage從API鏈接中的圖像填充uitableviewcell,問題是字符串是可選的,因為api結構中的索引可能有也可能沒有圖像。 這是代碼:

        let imageString = content[index].originalImageUrl

        cell.theImageView.sd_setImage(with: URL(string: imageString!), placeholderImage: UIImage(named: "placeholder.png"))

問題似乎是,如果originalImageURL為Nil,則由於找到nil而崩潰,因為它使我強制拆開該URL。 我希望情況是,如果url為nil,它將使用占位符圖像代替。 我怎樣才能做到這一點?

如果無法從提供的URL檢索圖像,則sd_setImage方法將使用placeholderImage ,即使URLnil

這意味着您可以簡單地向URL初始化程序提供不正確的URL字符串,而不是導致運行時錯誤,SDWebImage將僅使用占位符。

let imageString = content[index].originalImageUrl ?? ""

cell.theImageView.sd_setImage(with: URL(string: imageString), placeholderImage: UIImage(named: "placeholder.png"))

不要用力解包。 您可以使用if let

  if let imageString = content[index].originalImageUrl{
    cell.theImageView.sd_setImage(with: URL(string: imageString), placeholderImage: UIImage(named: "placeholder.png"))
    }else{
    cell.theImageView.image = UIImage(named: "placeholder.png")
}

您可以一行完成

cell.theImageView.sd_setImage(with: URL(string: content[index].originalImageUrl ?? ""), placeholderImage: UIImage(named: "placeholderSmall"))

在此處輸入圖片說明

暫無
暫無

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

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