我正在尝试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,则使用占位符图像。我怎样才能做到这一点?
不要用力展开。你可以使用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")
}
sd_setImage
方法使用placeholderImage
,以防图像无法从提供的URL
中检索到,所以即使URL
是nil
。
这意味着您只需向URL
初始化程序提供不正确的URL字符串,而不是导致运行时错误,SDWebImage将只使用占位符。
let imageString = content[index].originalImageUrl ?? ""
cell.theImageView.sd_setImage(with: URL(string: imageString), placeholderImage: UIImage(named: "placeholder.png"))