使用带有可选图像URL的UITableViewCell的SDWebImage

问题描述 投票:0回答:3

我正在尝试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,则使用占位符图像。我怎样才能做到这一点?

ios swift sdwebimage
3个回答
2
投票

不要用力展开。你可以使用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")
}

2
投票

sd_setImage方法使用placeholderImage,以防图像无法从提供的URL中检索到,所以即使URLnil

这意味着您只需向URL初始化程序提供不正确的URL字符串,而不是导致运行时错误,SDWebImage将只使用占位符。

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

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

1
投票

您可以在一行中执行此操作

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.