![](/img/trans.png)
[英]Handling download of image using SDWebImage while reusing 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
,即使URL
為nil
。
這意味着您可以簡單地向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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.